1

Is there a way to get the field type of a class in Python, for use as a type annotation?

import dataclasses

@dataclasses.dataclass
class A:
  field: str

def main() -> None:
  value: A.field = 123  # Want mypy to flag an error here

Where A.field is meant to refer to the type str, the type of A.field.

I'd like to do this to capture errors earlier for variables that may eventually be assigned to fields.

Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
edA-qa mort-ora-y
  • 30,295
  • 39
  • 137
  • 267
  • 2
    Nope. I don't think there is. – juanpa.arrivillaga Sep 14 '21 at 06:57
  • This is much too dynamic for a static type-checker to comprehend, I think. – Alex Waygood Sep 14 '21 at 07:21
  • 1
    @AlexWaygood I'm asking since I use a similar syntax from TypeScript, and was used to using it in C++. So in the general case it is something a static type checker could do. – edA-qa mort-ora-y Sep 14 '21 at 09:28
  • Nonetheless, I don't think this is something that any of Python's static type-checkers are currently capable of. Happy to be proven wrong! :) – Alex Waygood Sep 14 '21 at 09:30
  • can you say more about why you need the errors to be caught earlier? Why not have them raised when you're making an `A`? I think the answer to this question may answer your question – joel Sep 14 '21 at 22:18
  • @joel I want `value` to be the same type as `A.field` so that I can catch any potential type mismatches. I want the type dependent on the `field.A` type, in case it changes, or it's a complex type. – edA-qa mort-ora-y Sep 15 '21 at 08:25
  • i mean specifically why catch them _early_. You'll get a mypy error when you try to create an `A` with the wrong argument type anyway. This will hold even if sth changes. What's your use case for getting the error message at a different point in the code? – joel Sep 15 '21 at 09:17
  • @joel "later" might be in a different module or function, thus I won't know in my current function what is producing the wrong type. Or it may be an argument to a function which needs a type. Or the variable may need to pass through some untyped code along the way (thus erasing the tracking). – edA-qa mort-ora-y Sep 16 '21 at 07:44

0 Answers0