Search code examples
pythonpython-3.xpython-internals

Class property with space in it


Is it possible to do something like the following in Python?

class Object:
    
    def `two words`(self):
        return 'Worked!'

Depending on the dialect, in SQL you can usually do this with something like Person.[two words] or Person.`two words`, etc. Is it possible to do that in python?


Solution

  • It is possible. The class namespace isn't restricted to only identifiers, and this is intentional. However, the usual attribute access syntax instance.my attr will not work in this case so you must use getattr(instance, "my attr") instead.

    >>> def two_words(self):
    ...     return 'Worked!'
    ... 
    >>> Object = type("Object", (), {"two words": two_words})
    >>> obj = Object()
    >>> "two words" in dir(obj)
    True
    >>> getattr(obj, "two words")
    <bound method two_words of <__main__.Object object at 0x10d070ee0>>
    >>> getattr(obj, "two words")()
    'Worked!'
    

    It is also possible to create such an attribute with setattr.