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
So you can't assign a type to a class attribute outside a class definition. This would lead to inconsistent scenarios like below:
The good news is, you don't need to. The type is obtained from the class definition in your example, so you just say:
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.