du369
du369

Reputation: 821

__metaclass__ adding invalid attribute to class created?

metaclass adding invalid attribute to class?

Here is my code:

def __metaclass__(clsname, bases, dct):
    dct["key1"] = "value1"
    dct["invalid identifier"] = "value2"
    return type(clsname, bases, dct)


class Cls():
    pass



for name in dir(Cls):
    if not name.startswith("_"):
        print name

when I run it, I got:

>>> 
invalid identifier
key1
>>> 

Is is possible to access the invalid identifier?

Upvotes: 2

Views: 59

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121724

You can still access that identifier with getattr():

getattr(Cls, 'invalid identifier')

or directly on the class __dict__ mapping:

Cls.__dict__['invalid identifier']

You just cannot use direct attribute access as it is indeed not a valid identifier.

Upvotes: 2

Related Questions