8

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()
Ponkadoodle
  • 5,777
  • 5
  • 38
  • 62
  • "The problem is that I cannot refer to Test while it's still being defined". So? What possible kind of reference do you need **during definition**? The standard answer is None: the class definition is stable, consistent and invariant. **Behavior** can change. Definition should not change. What are you trying to do with this "varying definition" business? – S.Lott Apr 24 '10 at 22:37
  • The definition isn't changing. I just need a reference to the class, and for organization purposes, I'd prefer that I set that reference when the class is being defined. – Ponkadoodle Apr 24 '10 at 22:44
  • I understand what you're trying to do, but I'm not getting why you're trying to do it this way and what you're looking to accomplish. Can you elaborate a bit? It seems like more of an architectural then a "how do I coax python into...?" issue to me. – Aea Apr 24 '10 at 22:51
  • I'm writing a compiler, and I have types like int, str, etc. The `Test` class is an extremely simplified CompilerType. If I have something like str+str, I need to call a different function to add them than if it's str+int. So the dict is actually {CompilerType: add_function}. That means within the CompilerTypeStr, it's dict needs to contain a key of CompilerTypeStr. And I just wanted to know if there was a way of setting up the dict that looks (IMO) somewhat cleaner. – Ponkadoodle Apr 25 '10 at 00:47

5 Answers5

12

The class does in fact not exist while it is being defined. The way the class statement 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 as type) 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_dict is 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:

class Test:
    some_dict = {}
Test.some_dict[Test] = True

Use a class decorator (in Python 2.6 or later):

def set_some_dict(cls):
    cls.some_dict[cls] = True

@set_some_dict
class Test:
    some_dict = {}

Or use a metaclass:

class SomeDictSetterType(type):
    def __init__(self, name, bases, attrs):
        self.some_dict[self] = True
        super(SomeDictSetterType, self).__init__(name, bases, attrs)

class Test(object):
    __metaclass__ = SomeDictSetterType
    some_dict = {}
jfs
  • 399,953
  • 195
  • 994
  • 1,670
Thomas Wouters
  • 130,178
  • 23
  • 148
  • 122
  • It *could* be a module, but I'd prefer it be a class. If it was in a separate module, I'd have to do a bit of rearranging to prevent circular imports. Also, I'd need to have 20 tabs open when editing my project if all those classes were in different files. Anyways, thanks for telling me about Metaclasses. – Ponkadoodle Apr 24 '10 at 22:53
4

You could add the some_dict attribute after the main class definition.

class Test(object):
  pass
Test.some_dict = {Test: True}
Trey Hunner
  • 10,975
  • 4
  • 55
  • 114
1

I've tried to use classes in this way in the past, and it gets ugly pretty quickly (for example, all the methods will need to be class methods or static methods, and you will probably realise eventually that you want to define certain special methods, for which you will have to start using metaclasses). It could make things a lot easier if you just use class instances instead - there aren't really any downsides.

A (weird-looking) alternative to what others have suggested: you could use __new__:

class Test(object):
    def __new__(cls):
        cls.some_dict = {cls: True}

Test()

You could even have __new__ return a reference to the class and use a decorator to call it:

def instantiate(cls):
    return cls()

@instantiate
class Test(object):
    def __new__(cls):
        cls.some_dict = {cls: True}
        return cls
James
  • 3,191
  • 1
  • 23
  • 39
0

Thomas's first example is very good, but here's a more Pythonic way of doing the same thing.

class Test:
    x = {}
    @classmethod
    def init(cls):
        # do whatever setup you need here
        cls.x[cls] = True
Test.init()
darkfeline
  • 9,404
  • 5
  • 31
  • 32
0

You can also use a metaclass (a function here but there are other ways):

def Meta(name, bases, ns):
    klass = type(name, bases, ns)
    setattr(klass, 'some_dict', { klass: True })
    return klass

class Test(object):
    __metaclass__ = Meta

print Test.some_dict
fraca7
  • 1,178
  • 5
  • 11