python / python/mypy

mypy report custom builtins as not defined

Open
#12,172 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.