Issue 16740: Types created with PyType_FromSpec lack a module attribute. (original) (raw)

Types created using PyType_FromSpec do not have a module attribute by default. This caught me off guard.

$ python3 Python 3.2.3 (default, Oct 19 2012, 20:10:41) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information.

import xxlimited xxlimited.Null.module Traceback (most recent call last): File "", line 1, in AttributeError: module

Do we expect module authors to set the module attribute immediately after calling PyType_FromSpec?

To refresh your memory, non-heap types determine the module/name combo according to something like::

try:
    __module__, __name__ = tp_name.rsplit('.', 1)
except ValueError:
    __module__, __name__ = 'builtins', tp_name 

whereas heap types use something like::

__name__ = tp_name
@property
def __module__(self):
    return self.__dict__['__module__']

I think this is unnecessarily confusing, and, as far as I know, not documented anywhere.

I see from reading the commit logs that it was felt that by allowing users to set name (and therefore tp_name), it could have an unintended impact on the value module. If so, why didn't we just disallow setting name?

There are likely some unintended impacts of this decision, for example weird error message in other library functions:

import inspect inspect.getfile(xxlimited.Null) Traceback (most recent call last): File "", line 1, in File "/usr/lib/python3.2/inspect.py", line 415, in getfile object = sys.modules.get(object.module) AttributeError: module

Is there anything we can do here?