The normal way of creating a class in python does not allow for whitespace in the class name.
>>> class Foo Bar(object):
SyntaxError: invalid syntax
However, using the built-in type() function, we can create a class with whitespace in the name:
>>> C = type('Foo Bar', (object,),{})
>>> C
<class '__main__.Foo Bar'>
Is there any risks, or is it considered bad practice using class names with white space?
A class name can't have spaces. When you have a space-separated string in your class attribute, you're always giving your element several classes.
Note that a blank space should not be used between a method name and its opening parenthesis. This helps to distinguish keywords from method calls.
The class name can't contain a space, but it can contain hyphens or underscores. Any tag can have multiple space-separated class names.
There is no risk, the class __name__
is a writable attribute and it's not used for anything particularly important - just boring stuff like the repr and the help display.
If you try to assign non-string to it, there is a custom error message, which is strong evidence that Python devs had the chance to restrict to valid identifiers here, and they intentionally chose not to:
>>> class A:
... pass
...
>>> A.__name__ = '123Class'
>>> A.__name__ = 123
TypeError: can only assign string to 123Class.__name__, not 'int'
Here is Guido answering a similar question - about whether attribute names should be restricted to valid identifiers:
https://mail.python.org/pipermail/python-dev/2012-March/117441.html
I've spoken out on this particular question several times before; it is a feature that you can use any arbitrary string with
getattr()
andsetattr()
. However these functions should (and do!) reject non-strings.
The same reasoning applies to class names (which could also be stored as arbitrary strings in a module namespace). An example use-case for this feature: ensuring there's a consistent mapping between a sequence of class names and some external data source, even if the external data collides with Python reserved words or syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With