Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 206
jamesfranco Avatar asked Dec 31 '18 16:12

jamesfranco


People also ask

How do you type hint in Python?

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.

Should you type hint Python?

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.

What is Property () in Python?

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)

What is list from typing in Python?

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.


1 Answers

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.

like image 55
Michael0x2a Avatar answered Sep 29 '22 03:09

Michael0x2a