Following PEP 526 I'm wondering how to properly type hint an instance or class attribute that is decorated by a property. Do I type hint the underlying attribute or the name or the property?
Example of typing the attribute:
class Sample(object):
_target_dir: Path
@property
def target_dir(self):
pass
Or typing the property:
class Sample(object):
target_dir: Path
Or some other way? Is it the same for instance and class variables?
Here's how you can add type hints to our function: Add a colon and a data type after each function parameter. Add an arrow ( -> ) and a data type after the function to specify the return data type.
In his excellent article The State of Type Hints in Python, Bernát Gábor recommends that “type hints should be used whenever unit tests are worth writing.” Indeed, type hints play a similar role as tests in your code: they help you as a developer write better code.
In Python, property() is a built-in function that creates and returns a property object. The syntax of this function is: property(fget=None, fset=None, fdel=None, doc=None)
List. Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
You should decorate the underlying function that the @property
attribute is wrapping over:
class Sample:
@property
def target_dir(self) -> Path:
return Path("/foo/bar")
If your property is wrapping around some underlying private attribute, it's up to you whether you want to annotate that or not. I recommend you do, so you can benefit from typechecking wherever you use that private attribute, but whatever types you add there are going to be unrelated to the type of the property itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With