2

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.