RasmusN
RasmusN

Reputation: 168

Using whitespace in class names in Python

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?

Upvotes: 6

Views: 2734

Answers (2)

Arne
Arne

Reputation: 20187

Is there any risks, or is it considered bad practice using class names with white space?

It is absolutely considered bad practice, since PEP8 advises to use CapWords style for class names. The only technical difficulty you'll encounter is that such a whitespace-named class can't be instanciated with the usual syntax:

x = Foo Bar()  # SyntaxError

But the actual problem will always be that it is very unusual and any human reading your code or debugging your bugs will have a hard time. If I imagine seeing something like AttributeError: 'Foo Bar' object has no attribute 'x', I'd first try to find out what went wrong with the class name, because there is no way someone included a whitespace there.. right?

So please, just don't.

Upvotes: 3

wim
wim

Reputation: 363043

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() and setattr(). 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.

Upvotes: 6

Related Questions