Python singleton instantiation

  • Creational Patterns

    A creational pattern provides a particular instantiation mechanism. It can be aparticular object factory or even a class factory.

    This is an important pattern in compiled languages such as C, since it is harder togenerate types on-demand at run time.

page343image432

Useful Design Patterns

But this feature is built-in in Python, for instance the type built-in, which lets youdefine a new type by code:

   >>> MyType = type('MyType', (object,), {'a': 1})
   >>> ob = MyType()
   >>> type(ob)
   <class '__main__.MyType'>
   >>> ob.a
   1
   >>> isinstance(ob, object)
   True

Classes and types are built-in factories and you can interact with class and objectgeneration using meta-classes, for instance (see Chapter 3). These features are thebasics to implement the Factory design pattern and we won't further describe it inthis section.

Besides Factory, the only other creational design pattern from the GoF that isinteresting to describe in Python is Singleton.

Singleton

Singleton restricts instantiation of a class to one object.

The Singleton pattern makes sure that a given class has always only one livinginstance in the application. This can be used, for example, when you want to restricta resource access to one and only one memory context in the process. For instance,a database connector class can be a Singleton that deals with synchronization andmanages its data in memory. It makes the assumption that no other instance isinteracting with the database in the meantime.

This pattern can simplify a lot the way concurrency is handled in an application.Utilities that provide application-wide functions are often declared as Singletons.For instance, in web applications, a class that is in charge of reserving a uniquedocument ID would benefit from the Singleton pattern. There should be one andonly one utility doing this job.

Implementing the Singleton pattern is straightforward with the __new__ method:>>> class Singleton(object):

page343image16032 page343image16192 page343image16616 page343image17040

.........

def __new__(cls, *args, **kw):
    if not hasattr(cls, '_instance'):
     orig = super(Singleton, cls)

[ 326 ]

page343image25024 page343image25184
page344image416
...             cls._instance = orig.__new__(cls, *args, **kw)
...         return cls._instance
...
>>> class MyClass(Singleton):

... a =1
...
>>> one = MyClass()>>> two = MyClass()>>> two.a = 3
>>> one.a
3

Although the problem with this pattern is subclassing; all instances will be instancesof MyClass no matter what the method resolution order (__mro__) says:

>>> class MyOtherClass(MyClass):... b= 2
...
>>> three = MyOtherClass()

   >>> three.b
   Traceback (most recent call last):
     File "<stdin>", line 1, in ?
   AttributeError: 'MyClass' object has no attribute 'b'

To avoid this limitation, Alex Martelli proposed an alternative implementation basedon shared state called Borg.

The idea is quite simple. What really matters in the Singleton pattern is not thenumber of living instances a class has, but rather the fact that they all share the samestate at all times. So Alex Martelli came up with a class that makes all instances of theclass share the same __dict__:

   >>> class Borg(object):
  •    ...      _state = {}
    
  •    ...      def __new__(cls, *args, **kw):
    
  •    ...          ob = super(Borg, cls).__new__(cls, *args, **kw)
    
  •    ...          ob.__dict__ = cls._state
    
  •    ...          return ob
       ...
       >>> class MyClass(Borg):
    

... a =1
...
>>> one = MyClass()>>> two = MyClass()>>> two.a = 3
>>> one.a

[ 327 ]

Chapter 14

page344image15976 page344image16136 page344image16296
page345image424

Useful Design Patterns

3
>>> class MyOtherClass(MyClass):... b= 2
...
>>> three = MyOtherClass()
>>> three.b
2
>>> three.a
3
>>> three.a = 2
>>> one.a
2

This fixes the subclassing issue, but is still dependent on how the subclass codeworks. For instance, if __getattr__ is overridden, the pattern can be broken.

Nevertheless, Singletons should not have several levels of inheritance. A class that ismarked as a Singleton is already specific.

That said, this pattern is considered by many developers as a heavy way to deal withuniqueness in an application. If a Singleton is needed, why not use a module withfunctions instead, since a Python module is a Singleton?

The Singleton factory is an implicit way of dealing with the uniquenessin your application. You can live without it. Unless you are working in aframework à la Java that requires such a pattern, use a module insteadof a class. 





instantiation

 
英 [ɪnstænʃɪ'eɪʃən]      美 [ɪnstænʃɪ'eɪʃən]    
  • n.实例化;用具体例子说明;例示
释义常用度分布图海词统计
实例化
例示
用具体例..

instantiation是什么意思,词典释义与在线翻译:

行业释义

英英释义

Noun:
  1. a representation of an idea in the form of an instance of it;

    "how many instantiations were found?"

instantiation的用法和样例:

例句

  1. An object is instantiation of a class.
    对象是类的实列。
  2. Needed for instantiation and views.
    听 听 听 听 听-- raw symbol map.
  3. A new rule is created through the instantiation of a template.
    透过范本实例定义新的规则。
  4. Use delegate inference instead of explicit delegate instantiation.
    使用委托定义而不是直接的委托实例。
  5. The target instance to be created on template instantiation.
    将被创建在模板例示上的目标范例。
词性常用度分布图海词统计
名词

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值