3

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.

David R
  • 994
  • 1
  • 11
  • 27
  • In Python 3.7 this will be a valid syntax: https://docs.python.org/dev/whatsnew/3.7.html#pep-563-postponed-evaluation-of-annotations – Georgy Mar 14 '18 at 20:15
  • Possible duplicate of [Name not defined in type annotation](https://stackoverflow.com/questions/36286894/name-not-defined-in-type-annotation) – Georgy Mar 14 '18 at 20:19
  • Possible duplicate of [How do I specify that the return type of a method is the same as the class itself in python?](https://stackoverflow.com/questions/33533148/how-do-i-specify-that-the-return-type-of-a-method-is-the-same-as-the-class-itsel) – Jeyekomon Apr 23 '19 at 14:40

1 Answers1

2

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
Brad Solomon
  • 38,521
  • 31
  • 149
  • 235