mypy report custom builtins as not defined
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
I'm using the package gettext from the standard lib to translate texts inside the application. This will install the function _() in Python’s builtins namespace,
When registering a custom built-in in Pythons namespace then mypy does not recognize that as such and reports it as an unknown.
est.py:6: error: Name "_" is not defined
test.py:19: error: Name "_" is not defined
Found 2 errors in 1 file (checked 1 source file)
To Reproduce
Below is an example code that registers the _ as a bultin-in which can then be used as a standalone function in the code
class Translation:
def __init__(self, message: str):
self.message = message
def __str__(self) -> str:
translate = _
if translate is Translation:
return self.message
return translate(self.message)
@classmethod
def install(cls):
import builtins
builtins._ = cls
Translation.install()
s = _('something')
print(s)
Running mypy on this piece of code will report the following:
est.py:6: error: Name "_" is not defined
test.py:19: error: Name "_" is not defined
Found 2 errors in 1 file (checked 1 source file)
Expected Behavior
mypy should not report on custom defined built-ins that have been registered dynamically in the code.
A possible solution could be to do something similar to flake8 which allows to specify a config parameter
[flake8]
builtins = _
Actual Behavior
Reports that the dynamically defined builtins are not defined.
Your Environment
- Mypy version used: 0.931
- Mypy command-line flags: None
- Mypy configuration options from
mypy.ini(and other config files): None - Python version used: 3.10.2
- Operating system and version: Arch linux
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the supplied Translation.install() reproduction and the mypy command and configuration details in the report. Determine how dynamically assigned builtins are handled and whether a configuration-based solution is in scope; done means the reproduction no longer reports _ as undefined while genuinely undefined names remain diagnosed.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100