What is a singleton class in Python
Create a singleton in Python
Use a metaclass
I would Method # 2 recommend, but it is better to have one Metaclass to use as a base class. Here is an example implementation:
Or in Python3
If you want to run every time the class is called, add the following
to the statement in.
A few words about metaclasses. A metaclass is the Class of a class ; That is, a class is one Instance of your metaclass . You can find the metaclass of an object in Python using. Normal new style classes are of type. in the code above is of type, just like the (only) instance of is of type. When you invoke Logger with, Python first asks the metaclass of what to do so that it can withhold the instance creation. This process is the same as Python asking a class what to do by invoking you when referencing one of its attributes.
A metaclass essentially decides what the definition of a class means and how this definition is implemented. See, for example, http://code.activestate.com/recipes/498149/, which essentially recovers C-style s in Python using metaclasses. The thread What are your (specific) use cases for metaclasses in Python? also includes some examples related to declarative programming in general, particularly as used in ORMs.
In this situation, if you use the Method # 2 and a subclass defines a method is run every time when you call - because it does, responsible for calling the method that returns the stored instance. For a metaclass, only called once when the only instance is created. You want customize what it's called the class depending on their type.
Generally it is makes sense use a metaclass to implement a singleton. A singleton is special because is only created once and with a metaclass you can do the Customize the creation of a class . Using a metaclass gives you more control in case you need to customize the singleton class definitions in other ways.
Your singletons do not require multiple inheritance (since the metaclass is not a base class), but for Subclasses of the created class that use multiple inheritance you need to make sure that the singleton is present class is the class first / leftmost with a metaclass that redefines. It is very unlikely that this will be a problem. The instance dictation is not in the namespace of the instance so that it is not accidentally overwritten.
You will also hear that the singleton pattern violates the "Single Responsibility Principle" - every class should just do one thing . That way, you don't have to worry about messing up one thing the code does when you need to change another, as they are separate and encapsulated. The metaclass implementation passes this test . The metaclass is responsible for forcing the pattern and the created classes and subclasses don't have to be aware that they are singletons . Method # 1 fails this test, as you did with "MyClass itself is a function, not a class, so you cannot call any class methods from it."
Python 2 and 3 compatible version
In order to write something that works in both Python2 and 3, a slightly more complicated scheme has to be used. Since metaclasses are usually subclasses of type, you can use one to dynamically create an intermediate base class at run time with that as a metaclass, and then these than the base class of the public base class. It's harder to explain than to do, as shown below:
An ironic aspect of this approach is the use of subclasses to implement a metaclass. One possible benefit is that, unlike a pure metaclass, it returns.
You have probably already noticed this on another topic, but the implementation of the base class in your original post is incorrect. got to be referenced in the class , You must use or you are recursing , and is actually a static method that you have to hand over the class , not a class method, as the actual class has not yet been created when called. All of these things will also apply to a metaclass implementation.
Decorator who brings back a class
I originally wrote a comment, but it was too long so I'm going to add this one here. Method 4 is better than the other version of Decorator, but it takes more code than a singleton and it's not that clear what it does.
The main problems arise from the fact that the class is its own base class. Isn't it strange that a class is a subclass of a nearly identical class with the same name that is only present in its attribute? This also means you cannot define any methods that call the method of the same name in their base class with as they return. This means that your class cannot customize and cannot infer classes to call for.
When should the singleton pattern be used?
Your use case is one of the better examples if you want to use a singleton. You say in one of the comments: "For me, logging has always been a natural candidate for singletons." You have absolutely right .
When people say singletons are bad, the most common reason is that they are implicit common state are. While global variables and module imports of the top level the status explicit shared, other objects that are shared are generally instantiated. This is a good point with two exceptions .
The first and one that is mentioned in various places is when the singlets constant are. The use of global constants, especially enumerations, is widespread and is considered reasonable since none of the users can mess it up for another user . This also applies to a constant singleton.
The second exception, which is less mentioned, is the opposite - when the singleton just a data sink is not a data source (direct or indirect). Because of this, loggers feel like a "natural" use for singletons. As the different users the logger does not change in a way that other users are interested in is there not really shared status . This negates the primary argument against the singleton pattern and makes it based on it user friendliness for the task to be a sensible choice.
Here is a quote from http://googletesting.blogspot.com/2008/08/root-cause-of-singletons.html:
Well there is one kind of singleton that is fine. This is a singleton in which all reachable objects are immutable. If all objects are immutable, singleton does not have a global state because everything is constant. But it's so easy to turn that type of singleton into a mutable one that it's very slippery. That's why I'm against these singletons, not because they're bad, but because it's very easy for them to get bad. (As a side note, Java enumerations are only those kind of singletons. As long as you don't include a status in your enumeration, you're fine, so please don't.)
The other type of singletons that are semi-acceptable are the ones that don't affect the way your code runs. They have no "side effects". Logging is a perfect example. It's loaded with singletons and global state. It's acceptable (as it won't hurt you) as your application won't behave any differently whether or not a particular logger is enabled. The information here flows in one direction: From your application to the logger. Even if loggers have global status, as no information from loggers flows into your application, loggers are acceptable. You should still inject your logger if you want your test to confirm that something is being logged, but in general, loggers are not harmful despite being full of status.
- The number e is arbitrary
- Is tin malleable
- Excursions help students learn better
- What are some examples of smooth functions
- Whose death unexpectedly caused widespread public suffering
- What math is there in climate change
- When will Dombivli West develop
- What are Zucca melons used for?
- English is a language of emotions
- How is it that Google is always right
- What is the full form of DDWS
- What are the names of the people from Cyprus
- What was the first color film
- What was the first color film
- What is the strength of materials
- After the 10th which subject should we take?
- Why are some people hairier
- How do I remove centipedes
- Does FAU have a good football program
- What do Democrats think
- What is the ranking in KGEC
- How can I rent my domain name
- A quantization of the mass is possible
- Is IT 2nd shift good at MAIT