Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it a syntax error to have an object attribute named "del", "return" etc?

Tags:

python

I understand that one shouldn't be able to replace the behaviour of the "del" ("return" etc) keyword, but I do not understand why it is not possible to do this:

myobj.del(mystr)

What could the parser confuse it with? Is there a way to allow it?

Of course, I could use a different name, but I want to have a little custom wrapper around the AWS tool s3cmd and do things like s3cmd.del("s3://some/bucket/") and have the "del" handled by a __getattr__ in my s3cmd class... so the name "del" is something I'd be really happy to manage to use.

like image 442
vermillon Avatar asked Oct 26 '25 18:10

vermillon


1 Answers

That is because such words are keywords. Keywords in Python are reserved words that cannot be used as ordinary identifiers.

The list includes from the doc function keyword

>>> import keyword  
>>> import pprint
>>> pprint.pprint(keyword.kwlist)
['and',
 'as',
 'assert',
 'break',
 'class',
 'continue',
 'def',
 'del',
 'elif',
 'else',
 'except',
 'exec',
 'finally',
 'for',
 'from',
 'global',
 'if',
 'import',
 'in',
 'is',
 'lambda',
 'not',
 'or',
 'pass',
 'print',
 'raise',
 'return',
 'try',
 'while',
 'with',
 'yield']

The reason as to why is beautifully mentioned in Konrad's comment

There’s nothing magical about keywords. However, it makes parsers vastly easier to write when disallowing keywords for identifiers. In particular, it makes it easier to provide human-readable error messages for parse errors, because the parser is able to infer more context about the error.

like image 96
Bhargav Rao Avatar answered Oct 29 '25 08:10

Bhargav Rao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!