Search code examples
pythonpropertiespython-typing

Proper way to type hint a private property in python


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?


Solution

  • 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.