3

why is functions like len and max not a reserved keyword in python. Following are the only reserved words http://docs.python.org/2/reference/lexical_analysis.html#keywords

asked Mar 20, 2014 at 7:36
6
  • Because they are only function names? Commented Mar 20, 2014 at 8:02
  • This is similar for most object oriented languages (especially the dynamic ones and those with the "everything is an object" approach). Keywords are only the core syntax. All the classes, even those that belong to the standard libraries, are nothing special compared to classes written by the user. (and I really do not see why there should be a reason to down vote this question) Commented Mar 20, 2014 at 8:59
  • but why should one be allowed to redeclare such a variable. It's a nightmarish scenario Commented Mar 20, 2014 at 9:12
  • 2
    why shouldn't I be allowed to write my own def max or def len for a given class? Commented Mar 20, 2014 at 15:17
  • 1
    @WebDeveloper: Why shouldn't you be available? Why should the language grammar have to know about standard library functions? Redeclaring definitions is actually an orthogonal concern, but even so, what if I wanted to wrap len with a pass-through logger? Commented Mar 20, 2014 at 15:29

1 Answer 1

6

It doesn't make sense to privilege the built in functions like len, str, and so on, because that would require a core language change. To add len and so on to the core language would require changes to the parser to recognize and reject changes to them. And adding parser changes can be quite risky for a very small benefit, and it could also impact performance.

When on the other hand, it keeps the language clean and simple, and enables useful edge cases, for example redefinitions of len, etc. While this might scare you, I guarantee you it was useful to someone somewhere.

If you're paranoid that someone overwrote len, you can always do the following:

from __builtins__ import len as SUPERSECURELEN

You cannot modify the builtins module. So its safe.

answered Mar 20, 2014 at 15:18
1
  • "You cannot modify the builtins module" ... it seems you can (testsed on py 2.7 and 3.7): __builtins__.len=lambda x: -42; len([]) Commented Dec 20, 2021 at 14:08

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.