Is it reasonable to use a decorator to instantiate a singleton in Python?

Suppose I have a class like this:

class Foo(object):
    # some code here

As it happens, Foo is a singleton. There are numerous ways to write singletons in Python, but most of them don’t really feel very Pythonic to me. If someone else has a particularly strong reason for instantiating or subclassing my class, I see no reason to go out of my way to make things unreasonably difficult for them (beyond a minimal “this is not part of the public API and might break everything” hint).

So I hit upon this idea:

def singleton(cls):
    return cls()

@singleton
class foo_instance(object):  # note lower case
    # some code here

I had to write singleton() myself because operator.call() isn’t a thing for some strange reason.

Obviously, you can still just do type(foo_instance) and instantiate by hand, but the lack of a publicly visible class makes it obvious (to me) that you’re not really supposed to do that (in much the same way as you’re not supposed to mess around with type(enum.Enum) in 3.4+), and I think it looks cleaner than an underscore-prefixed “private” class such as class _Foo.

Is this a reasonable way to go about making a class singular?

7

I think the simplest, most Pythonic way to implement a singleton class is with inheritance:

class Singleton(object):

    _instances = {}

    def __new__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = object.__new__(cls, *args, **kwargs)
        return cls._instances[cls]


class Foo(Singleton):  # Foo 'is a' Singleton
    pass

Now the usage is simple:

>>> foo1 = Foo()
>>> foo2 = Foo()
>>> foo1 is foo2
True

and won’t break in the case you identify above:

>>> foo3 = type(foo1)()
>>> foo1 is foo3
True

You can also inherit from Foo; the child class will also be a Singleton.

One issue to be aware if is that if you implement Foo.__init__, it will be called every time Foo() is called. If that is undesirable, move the initialisation to the constructor (i.e. implement Foo.__new__ instead, remembering to call the super constructor too).

Yes! It is absolutely reasonable… (I’d think)

I have “invented” (I should probably say “re-invented”) it myself some long time ago, and still use it where needed. Here, “where needed” usually means “where it makes the intention clearer” and not “where I want to make sure nobody tricks their way to a second instance of that class”.

I actually find the solution provided by @jonrsharpe not to be very Pythonic. It’s a nice trick for sure! Even if you don’t want to do it via inheritance but via a decorator, the general idea can be applied. But a constructor that returns an existing instance seems not Pythonic to me at all.

So, yes, simply hiding the class behind the sole instance does all that’s intended. The fact that type(foo_instance)() will create a new instance does not detract from it. If one was bound to do similar things with other Python code, it was trivially simple to do so. Otherwise Python would also need to forbid external access to underscore methods, etc. So, it boils down to “we are all consenting adults here”.

Note: I know this question is rather old, but I just found it when I was looking for a better (more Pythonic?) way to achieve the same out of curiosity. But the alternatives (even if they are clever and working well), don’t seem to be any better. Thus, the simple design is probably best …

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

Is it reasonable to use a decorator to instantiate a singleton in Python?

Suppose I have a class like this:

class Foo(object):
    # some code here

As it happens, Foo is a singleton. There are numerous ways to write singletons in Python, but most of them don’t really feel very Pythonic to me. If someone else has a particularly strong reason for instantiating or subclassing my class, I see no reason to go out of my way to make things unreasonably difficult for them (beyond a minimal “this is not part of the public API and might break everything” hint).

So I hit upon this idea:

def singleton(cls):
    return cls()

@singleton
class foo_instance(object):  # note lower case
    # some code here

I had to write singleton() myself because operator.call() isn’t a thing for some strange reason.

Obviously, you can still just do type(foo_instance) and instantiate by hand, but the lack of a publicly visible class makes it obvious (to me) that you’re not really supposed to do that (in much the same way as you’re not supposed to mess around with type(enum.Enum) in 3.4+), and I think it looks cleaner than an underscore-prefixed “private” class such as class _Foo.

Is this a reasonable way to go about making a class singular?

7

I think the simplest, most Pythonic way to implement a singleton class is with inheritance:

class Singleton(object):

    _instances = {}

    def __new__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = object.__new__(cls, *args, **kwargs)
        return cls._instances[cls]


class Foo(Singleton):  # Foo 'is a' Singleton
    pass

Now the usage is simple:

>>> foo1 = Foo()
>>> foo2 = Foo()
>>> foo1 is foo2
True

and won’t break in the case you identify above:

>>> foo3 = type(foo1)()
>>> foo1 is foo3
True

You can also inherit from Foo; the child class will also be a Singleton.

One issue to be aware if is that if you implement Foo.__init__, it will be called every time Foo() is called. If that is undesirable, move the initialisation to the constructor (i.e. implement Foo.__new__ instead, remembering to call the super constructor too).

Yes! It is absolutely reasonable… (I’d think)

I have “invented” (I should probably say “re-invented”) it myself some long time ago, and still use it where needed. Here, “where needed” usually means “where it makes the intention clearer” and not “where I want to make sure nobody tricks their way to a second instance of that class”.

I actually find the solution provided by @jonrsharpe not to be very Pythonic. It’s a nice trick for sure! Even if you don’t want to do it via inheritance but via a decorator, the general idea can be applied. But a constructor that returns an existing instance seems not Pythonic to me at all.

So, yes, simply hiding the class behind the sole instance does all that’s intended. The fact that type(foo_instance)() will create a new instance does not detract from it. If one was bound to do similar things with other Python code, it was trivially simple to do so. Otherwise Python would also need to forbid external access to underscore methods, etc. So, it boils down to “we are all consenting adults here”.

Note: I know this question is rather old, but I just found it when I was looking for a better (more Pythonic?) way to achieve the same out of curiosity. But the alternatives (even if they are clever and working well), don’t seem to be any better. Thus, the simple design is probably best …

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật