Search code examples
pythonmethodstypesparameters

How to hint custom types for method parameters, where both the type and method is in the same class?


How do I hint that the symbol parameter in the function add_symbol, is a type of Lexer.symbol? It says that it's not defined. I tried a few things and I don't know what will work.

class Lexer:
    class symbol:
        def __init__(self, lexeme: str, token: str):
            self.lexeme: str = lexeme
            self.token: str = token

    class SymbolTable:
        def __init__(self):
            self.symbols: list[Lexer.symbol] = [] # This works
            # self.symbols: list[symbol] = [] # This does not

        def add_symbol(self, symbol: Lexer.symbol): # This says undefined
            pass

        def add_symbols(self, symbol: list[symbol]): # This too
            pass

Should I declare the symbol class outside of the Lexer class instead? I kinda do want the it to be inside though. Thank you very much.

I tried it with and without the Lexer class to access the symbol, but it still says it's undefined.


Solution

  • Just add from __future__ import annotations at the beginning of the file