Why can’t attribute names be Python keywords?

Because parser is simpler when keywords are always keywords, and not contextual (e.g. if is a keyword when on the statement level, but just an identifier when inside an expression — for if it’d be double hard because of X if C else Y, and for is used in list comprehensions and generator expressions).

So the code doesn’t even get to the point where there’s attribute access, it’s simply rejected by the parser, just like incorrect indentation (which is why it’s a SyntaxError, and not AttributeError or something). It doesn’t differentiate whether you use if as an attribute name, a variable name, a function name, or a type name. It can never be an identifier, simply because parser always assigns it “keyword” label and makes it a different token than identifiers.

It’s the same in most languages, and language grammar (+ lexer specification) is the documentation for that. Language spec mentions it explicitly. It also doesn’t change in Python 3.

Also, just because you can use setattr or __dict__ to make an attribute with a reserved name, doesn’t mean you should. Don’t force yourself/API user to use getattr instead of natural attribute access. getattr should be reserved for when access to a variable attribute name is needed.

Leave a Comment