Here’s a very simple example of what I’m trying to get around:
class Test(object):
some_dict = {Test: True}
The problem is that I cannot refer to Test while it’s still being defined
Normally, I’d just do this:
class Test(object):
some_dict = {}
def __init__(self):
if self.__class__.some_dict == {}:
self.__class__.some_dict = {Test: True}
But I never create an instance of this class. It’s really just a container to hold a group of related functions and data (I have several of these classes, and I pass around references to them, so it is necessary for Test to be it’s own class)
So my question is, how could I refer to Test while it’s being defined, or is there something similar to __init__ that get’s called as soon as the class is defined? If possible, I want self.some_dict = {Test: True} to remain inside the class definition. This is the only way I know how to do this so far:
class Test(object):
@classmethod
def class_init(cls):
cls.some_dict = {Test: True}
Test.class_init()
The class does in fact not exist while it is being defined. The way the
classstatement works is that the body of the statement is executed, as a block of code, in a separate namespace. At the end of the execution, that namespace is passed to the metaclass (such astype) and the metaclass creates the class using the namespace as the attributespace.From your description, it does not sound necessary for Test to be a class. It sounds like it should be a module instead.
some_dictis a global — even if it’s a class attribute, there’s only one such attribute in your program, so it’s not any better than having a global — and any classmethods you have in the class can just be functions.If you really want it to be a class, you have three options: set the dict after defining the class:
Use a class decorator (in Python 2.6 or later):
Or use a metaclass: