Search code examples
pythonpython-3.xsyntax-error

Python: Name "from" as parameter throws Syntax error


I am working on API and I really cannot rename variable name to process things fast but I cannot make run the code(Python 3.11).

The problem:

def __init__(self, from: str = None)
    self.from = from

when I try to run this piece of beautifully written gem, I got an error.

def __init__(self, from: str = None
                   ^^^^
SyntaxError: invalid syntax

Even the pylance had problem with the syntax but I manage to fix it with # type: ignore at the beginning of the script.

Any advice?

Editor: VSCode

I have tried Google but didn't help much. :)


Solution

  • The error message isn't very clear, but from is a reserved keyword

    https://docs.python.org/3/reference/lexical_analysis.html#keywords

        ...
    except Exception as ex:
        raise ValueError("oops") from ex
    
    def my_generator(some_iter):
        ...
        yield from some_iter
    
    from foo import bar
    

    If you must to keep the name (say, frontending some other frozen frozen API), you could extract it from **kwargs

    def __init__(self, *args, **kwargs):
        self._from = kwargs["from"]
    

    You may also have to be careful creating instance of the class

    AwkwardFromArgClass(**{"from": "from value"})