[Python-ideas] Syntax for easy binding __name__, __module__, __qualname__ to arbitrary objects

Piotr Duda duda.piotr at gmail.com
Thu May 9 12:29:45 CEST 2013


In discussion about http://www.python.org/dev/peps/pep-0435/ being
mentioned problems with enums created with functional syntax:
- need for explicit pass of type name to "function" that create enum type:
Animals = Enum('Animals', 'dog cat bird')
which violates DRY
- pickling which requires __module__ atribute to be set, proposed
solutions for this was either use non-portable and fragile _getframe
hack, or explicit pass module name:
Animals = Enum('animals.Animals', 'dog cat bird')
aside violating DRY, this solution also has other problems, it won't
work correctly if module is executed directly, and will break if
pickling nested classes from http://www.python.org/dev/peps/pep-3154/
will be implemented (it may by bypassed by either provide separate
arguments for module and type name, or using different separator for
separating module and class name)

These also apply for other objects like NamedTuple or mentioned NamedValues.

To solve these problems I propose to add simple syntax that assigns
these attributes to arbitrary object:
def name = expression
other possible forms may be:
def name from expression
class name = expression
class name from expression
name := expression # new operator


which would be equivalent for:
_tmp = expression
_tmp.__name__ = 'name'
_tmp.__qualname__ = ... # corresponding qualname
_tmp.__module__ = __name__
# apply decorators if present
name = _tmp

with new syntax declaring Enum will look like
def Animals = Enum('dog cat bird')

as pointed by Larry it may be done using existing syntax in form:
@Enum('dog cat bird')
def Animals(): pass

but it's ugly, and may by confusing.


Other examples:
def MyTuple = NamedTuple("a b c d")
def PI = NamedValue(3.1415926)


--
闇に隠れた黒い力
弱い心を操る



More information about the Python-ideas mailing list