Replies: 6 comments 8 replies
-
|
Currently this is not supported. There was a discussion about potentially adding Right now the most correct way is to have some attribute defined as such: class MyClass:
def __init__(self) -> None:
self.attr: int | None = None
def method(self) -> None:
self.attr = 1 # or whatever |
Beta Was this translation helpful? Give feedback.
-
|
I'm curious what your desired behavior would be for such an attribute? Always emit an error/warning when accessing it, but also infer the resulting type as |
Beta Was this translation helpful? Give feedback.
-
|
I am running into this when trying to type the open search bulk load responses. There's so many permutations of these objects that I really just wanna be able to type it as a single object type in the listwith certain attributes that may or may not exist. I can type this really easily in type script, but there seems to be zero ways to do it in Python. |
Beta Was this translation helpful? Give feedback.
-
|
This is a problem that is often ignored while being blatantly obvious. Let's assume: class Address:
...
class Person:
name: str
address: Address | NoneNow, the only option to do a partial update of a person is class PartialUpdatePerson(TypedDict):
name: NotRequired[str]
address: NotRequired[Address | None]We need this. |
Beta Was this translation helpful? Give feedback.
-
|
I feel like the existing NotRequired[TYPE]would does exactly what we need, just right now limited to So all we need now, is to allow it to be used in classes as well. |
Beta Was this translation helpful? Give feedback.
-
|
Unfortunately, this is not a hypothetical. Here is an example of this in the wild, in a reasonably well-known package: https://github.com/perforce/p4python/blob/31ac0a69eb508dcf557c9a620f3a109f8fec5817/P4.py#L124 spec = P4.Spec()
# Attribute names are restricted, so most assignments are disallowed; the following will throw
# spec.foo = "foo"
# This will throw AttributeError, per above
# print(spec.comment)
# But it can be assigned to, which then makes it available
spec.comment = "make it so"
print(spec.comment) # This now prints as expected |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Cross posting from Stack Overflow:
How do I do a type hint for attribute that might not exist on the object in Python?
For example:
So, concretely:
Slots may not always be involved, but I can see wanting to do something similar when specifying a
Protocol.Beta Was this translation helpful? Give feedback.
All reactions