-
Notifications
You must be signed in to change notification settings - Fork 1.4k
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
Wrong type for property in dataclass if there exists an InitVar of the same name #4113
Comments
You are declaring the symbol from dataclasses import InitVar, dataclass, field
@dataclass
class Foo:
_bar: list[str] = field(init=False)
baz: InitVar[str] = ''
def __post_init__(self, baz):
if type(baz) is property:
self._bar = ['default', 'bar']
else:
self._bar = baz.split(',')
@property
def bar(self) -> str:
return ','.join(self._bar)
f1 = Foo()
print(f'f1.bar is {f1.bar}')
f2 = Foo(baz='non,default,bar')
print(f'f2.bar is {f2.bar}') |
Yes, I agree that this namespace conflict should result in errors, specifically those in line 6. However, I'd argue that referring to the variable outside of
In other words, the following code fragment from dataclasses import InitVar, dataclass, field
@dataclass
class Foo:
_bar: list[str] = field(init=False)
bar: InitVar[str] = '' # type: ignore
def __post_init__(self, bar):
if type(bar) is property:
self._bar = ['default', 'bar']
else:
self._bar = bar.split(',')
@property
def bar(self) -> str:
return ','.join(self._bar)
f1 = Foo()
print(f'f1.bar is {f1.bar}') # f1.bar should be str
f2 = Foo(bar='non,default,bar')
print(f'f2.bar is {f2.bar}') # f2.bar should be str should not report any errors as I believe this is important as it allows class Foo:
def __init__(self, bar: str = 'default,bar'):
self._bar = bar.split(',')
@property
def bar(self) -> str:
return ','.join(self._bar) This way, there will be a consistent naming in both the (class) Foo(bar: str = '')
(property) bar: str instead of as: (class) Foo(baz: str = '')
(property) bar: str as per your suggestion. |
You've added a |
Describe the bug
From https://docs.python.org/3/library/dataclasses.html:
When a
dataclass
has both anInitVar
and@property
with the same name, outside of__init__()
and__post_init__()
, the variable should have the type as described by the@property
annotation, sinceInitVar
s are not used outside of__init__()
and__post_init__()
.To Reproduce
Simply create a Python file with the following code
Expected behavior
The type of the property outside of
__init__()
and__post_init__()
should be the type of the property, or at the very least, referencing these variables should not be treated as an errorScreenshots or Code
The errors in line 6 are valid (variable of same name with different types), but lines 19 and 22 should not be an error.
VS Code extension or command-line
Command line, version 1.1.277
The text was updated successfully, but these errors were encountered: