Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 821
RasmusN Avatar asked Aug 03 '18 06:08

RasmusN


People also ask

Can you have spaces in class names?

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.

Can method names have spaces?

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.

Can CSS classes have spaces?

The class name can't contain a space, but it can contain hyphens or underscores. Any tag can have multiple space-separated class names.


1 Answers

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.

like image 142
wim Avatar answered Sep 20 '22 02:09

wim