Non self attributes cannot have type hints (or how to add type hint for class attributes )

136 views Asked by At

I tried to add type hint for class attributes but Pycharm doesn't support it?

Python version:3.9 Platform: win10

class Person:
    name: str
    id: int


msg: Person = Person()
msg.name: str = 'test'  # err msg is 'Non self attributes cannot have type hints'

any advices? or just using msg.name: str = 'test' and ignore Pycharm err msg

1

There are 1 answers

1
Mark On

So you can't assign a type to a class attribute outside a class definition. This would lead to inconsistent scenarios like below:

class A:
   x: int

a = A()
a.x: int = 1

b = A()
b.x: str = 'test'
# What is the type of the x attribute now?
# Types must be consistent across class instances

The good news is, you don't need to. The type is obtained from the class definition in your example, so you just say:

class Person:
    name: str
    id: int


msg = Person()
msg.name = 'test'

If 'test' were anything other than a string your type checker would raise an error.

An important takeaway is using types doesn't mean you have to use types everywhere - just enough for the types to be well defined. In general functions should have all parameters and return types annotated, and classes should have type annotations as you've done, but outside of this often types are inferable. Notice in the new example I didn't add a type on the msg line - this type should be inferable.