Skip to content

mypy report custom builtins as not defined #12172

Open
@svartkanin

Description

@svartkanin

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions