You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Disallow access to instance variable via class #240
The OP has it as writing—I ran into this erroneously reading a variable; consider:
from __future__ importannotationsimportloggingfromtypingimportTypeclassA:
def__init__(self):
self._log=logging.getLogger()
pass@classmethoddeffrom_spam(cls: Type[A], spam):
ifspam:
cls._log.warning("got spam") # accepted, but should be an errorreturncls()
I ran into a situation which is almost the opposite problem of the original one: not only a given attribute is deliberately accessible by both the instance and the class, but the type in each case different. Unsurprisingly mypy complains about Incompatible types in assignment.
With Python 3.12.6 and mypy 1.11.2, mypy says still nothing on this case, but Pylint and Pylance do it, and there is an error during the code execution.
mypy says Cannot assign to final attribute "id" mypy(misc) on the self.id = 10 line, which is incorrect because self.id defined in the constructor is considered as an instance attribute by Python, and not the class attribute A.id. :/
Pylance does exactly the same mistake. >_< !!!
Activity
JukkaL commentedon May 17, 2015
Actually, I'm no longer convinced that this is a bug. Turning this into an enhancement proposal.
gvanrossum commentedon May 17, 2015
Yeah, this may just be a somewhat unconventional wy of setting the default.
JukkaL commentedon Oct 13, 2015
Postponing this as I'm not sure if this is a good idea but might still be worth considering.
mark-kubacki commentedon Feb 18, 2022
The OP has it as writing—I ran into this erroneously reading a variable; consider:
gsakkis commentedon Sep 11, 2023
I ran into a situation which is almost the opposite problem of the original one: not only a given attribute is deliberately accessible by both the instance and the class, but the type in each case different. Unsurprisingly mypy complains about
Incompatible types in assignment.Minimal example:
I tried annotating
xboth as an instance and class variable but this caused aName "x" already definederror without getting rid of the first one:vtgn commentedon Oct 15, 2024
Hello!
2024 here! What are the news since 2013?!
With Python 3.12.6 and mypy 1.11.2, mypy says still nothing on this case, but Pylint and Pylance do it, and there is an error during the code execution.
Plus, for this close similar case:
mypy says Cannot assign to final attribute "id" mypy(misc) on the self.id = 10 line, which is incorrect because self.id defined in the constructor is considered as an instance attribute by Python, and not the class attribute A.id. :/
Pylance does exactly the same mistake. >_< !!!
Prohibit access via class for instance-only attributes (python#20855)