6

I write a script for myself on python, I use the dataclass library, I have a ready-made DTO written in Java, which I try to repeat on the python, there is a field called "from", what can I call this field in python, because I can't call him the same way?

I use python 3.7 and dataclass_json

@dataclass_json
@dataclass
class Direction:
    from: Optional[str]
    to: Optional[str]
from: Optional[str]
    ^

SyntaxError: invalid syntax

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264

1 Answers1

3

from is a reserved word in Python. It is used in raise statements to assign a parent exception, and in yield from to delegate to an iterator.

A common workaround is to append an underscore if you wish to use a reserved word as a variable (e.g., use from_). You can see some examples of this in the operator module, which defines functions like in_, is_, and not_. This frequently applies to built in functions and classes too, even though they aren't technically reserved. Notice that in the documentation, prepending an underscore has slightly special meaning, while appending one does not.

Fun bonus fact: the keyword module has a full list of keywords (kwlist) and let's you check if a word is a keyword (iskeyword) directly in the interpreter. This applies even for new keywords that come from a __future__ import.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264