0
class Session:
    

    @staticmethod
    def load_from_json(json_path:str) -> Session:
        pass

Above throws a NameError: name 'Session' is not defined. Is using itself for the type hint in its definition impossible?

Inyoung Kim 김인영
  • 1,434
  • 1
  • 17
  • 38
  • Is the function supposed to be returning an instance of the class? – Boskosnitch Feb 09 '21 at 01:21
  • @Boskosnitch Yes. It is supposed to read a json file and create an instance of `Session `using the parameters specified in the json file. – Inyoung Kim 김인영 Feb 09 '21 at 01:22
  • Does this answer your question? [How to overload \_\_init\_\_ method based on argument type?](https://stackoverflow.com/questions/141545/how-to-overload-init-method-based-on-argument-type) – Boskosnitch Feb 09 '21 at 02:34

2 Answers2

5

Use:

def ... -> 'Session':

Session is not defined when you use it, so you must use a string (Python 3.8).

hussic
  • 1,816
  • 9
  • 10
0
  1. Class constructors are defined with init(self,..)
  2. init methods should always have 'None' as the return type if you must include a return type in the type hints.
  3. The method posted is not a class method, as it does not alter any class attributes or behaviors.

To construct the class instance:

class Session:
    def __init__(self,json_path: str) -> None:
        do stuff...

Feel free to correct me if I'm misunderstanding anything

Boskosnitch
  • 774
  • 3
  • 8