4

I've been writing some code in python 3.6 in which the class state can be saved to disk, and then loaded. It goes something along the lines of:

class MyClass(object):
    @staticmethod
    def Load(filename) -> MyClass:
        return MyClass()

print(MyClass.Load('test.pkl'))

When using the typing, I get an error:

Traceback (most recent call last):
  File "tmp/test.py", line 2, in <module>
    class MyClass(object):
  File "tmp/test.py", line 4, in MyClass
    def Load(MyClass, filename) -> MyClass:
NameError: name 'MyClass' is not defined

which suggests that the type name is not available at the time the method is type-checked. However, when actually running the code (when removing the typing) the program proceeds as expected:

>> python tmp/test.py
<__main__.MyClass object at 0x7f249449a550>

The code with typing removed:

class MyClass(object):
    @staticmethod
    def Load(filename):
        return MyClass()

print(MyClass.Load('test.pkl'))

The same error occurs when using the @classmethod decorator. Is there something that I'm missing with respect to the way that the typing feature works? Is there a more "pythonic" way to write this code? (The loading implementation is significantly different from the default constructor, hence the desire to write a different function instead of using keyword arguments).

David Chan
  • 383
  • 1
  • 2
  • 9

0 Answers0