Skip to content

Variable assignment on module reference reported as "Module has no attribute <variable_name>" #7171

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
timmwagener opened this issue Jul 8, 2019 · 2 comments

Comments

@timmwagener
Copy link

timmwagener commented Jul 8, 2019

Please provide more information to help us understand the issue:

  • Problem
  • Are you reporting a bug, or opening a feature request?
    • Bug
  • Please insert below the code you are checking with mypy, or a mock-up repro if the source is private. We would appreciate if you try to simplify your case to a minimal repro.
# a.py
import sys
this = sys.modules[__name__]
this.serializable_classes = {}  # a.py:15: error: Module has no attribute "serializable_classes"
setattr(this, "serializable_classes", {})  # alternative without mypy error
  • What is the actual behavior/output?
    • error: Module has no attribute "serializable_classes"
  • What is the behavior/output you expect?
    • No error. It seems mypy applies rules for accessing a name from a module, while it really is an assignment. Why would the previous presence of a variable name in a module namespace matter under these circumstances?
  • What are the versions of mypy and Python you are using?
$ tox -e mypy
mypy installed: mypackage==0.0.1,mypy==0.711,mypy-extensions==0.4.1,typed-ast==1.4.0
mypy run-test-pre: PYTHONHASHSEED='349'
mypy run-test: commands[0] | python --version
Python 3.7.3
  • What are the mypy flags you are using? (For example --strict-optional)
# mypy.ini
[mypy]
warn_return_any = True
warn_unused_configs = True
# and some import ignores below
@timmwagener
Copy link
Author

Just realizing, there may be no need to assign to this on import time. I guess this should still work:

import sys
this = sys.modules[__name__]
serializable_classes = {}

def set(key, value):
    this.serializable_classes[key] = value

This fixes the error in mypy, however it is still theoretically an unnecessary and misleading error when the syntax from above is used, isn't it?

@ilevkivskyi
Copy link
Member

Mypy doesn't support monkey-patching modules and classes. Using setattr() (or a # type: ignore) is a possible work-around.

saska added a commit to saska/pandas that referenced this issue Oct 16, 2019
Switched from obj.__setattr__(...) to setattr(obj, ...)
python/mypy#7171 (comment)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants