This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author jaraco
Recipients jaraco
Date 2022-02-03.01:08:28
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1643850508.65.0.917170259408.issue46619@roundup.psfhosted.org>
In-reply-to
Content
Attempting to define a lazy-loaded property for a module, I found [this guidance](https://stackoverflow.com/a/52018676/70170) referencing [module attribute access](https://docs.python.org/3/reference/datamodel.html#customizing-module-attribute-access) in the Python docs as a means of customizing attribute access.

I followed that guidance, but found that doctests don't have access to those attributes in its execution. Consider this reproducer:

```
"""
>>> print(static_property)
static value
>>> print(lazy_property)
lazy value
"""
# text.py
import types
import sys


static_property = 'static value'


class _Properties(types.ModuleType):
    @property
    def lazy_property(self):
        return 'lazy value'


sys.modules[__name__].__class__ = _Properties
```

Run that with `python -m doctest text.py` and it fails thus:

```
**********************************************************************
File "/Users/jaraco/draft/text.py", line 4, in text
Failed example:
    print(lazy_property)
Exception raised:
    Traceback (most recent call last):
      File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/doctest.py", line 1346, in __run
        exec(compile(example.source, filename, "single",
      File "<doctest text[1]>", line 1, in <module>
        print(lazy_property)
    NameError: name 'lazy_property' is not defined
**********************************************************************
1 items had failures:
   1 of   2 in text
***Test Failed*** 1 failures.
```

Same error using the `__getattr__` technique:

```
"""
>>> print(static_property)
static value
>>> print(lazy_property)
lazy value
"""

static_property = 'static value'


def __getattr__(name):
    if name != 'lazy_property':
        raise AttributeError(name)
    return 'lazy value'
```

I suspect the issue is that doctests runs with locals from the module's globals(), which won't include these lazy properties.

It would be nice if doctests could honor locals that would represent the properties available on the module.
History
Date User Action Args
2022-02-03 01:08:28jaracosetrecipients: + jaraco
2022-02-03 01:08:28jaracosetmessageid: <1643850508.65.0.917170259408.issue46619@roundup.psfhosted.org>
2022-02-03 01:08:28jaracolinkissue46619 messages
2022-02-03 01:08:28jaracocreate