Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use type hinting in Python when loading objects

How can I alert python of the return type of a pickle.load() command within a class where load() command returns an object of the class.

I had hoped the straight-forward

class myClass:

    @classmethod
    def load(cls, filename) -> myClass:
        with open(filename,'rb') as f:
            return pickle.load(f)

would work, but python complains that myClass is not defined.

I'd like for python to know the class type for code completion, etc.

like image 736
David R Avatar asked Feb 23 '26 18:02

David R


1 Answers

As you're probably aware, at the time when you define the classmethod, myClass doesn't yet exist, so you can't reference it directly.

The prescribed alternative is to use string representations of the object. It's not perfect, but at the end of the day type-hinting is not a strict means of enforcement; it's just an informal hint.

From PEP 484:

When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.

class myClass:
    @classmethod
    def load(cls, filename) -> 'myClass':
        with open(filename,'rb') as f:
            return pickle.load(f)

In fact, there's an example very similar to yours from that PEP:

class Tree:
    def __init__(self, left: 'Tree', right: 'Tree'):
        self.left = left
        self.right = right
like image 51
Brad Solomon Avatar answered Feb 26 '26 07:02

Brad Solomon