[Tutor] Doubt
Peter Otten
__peter__ at web.de
Mon Jan 7 15:43:51 EST 2019
Amit Yadav wrote:
> How can simply typing
>
> print "hello world"
>
> work?
> Like without including any header file or import statements how can it
> work.
In Python 2 print is part of the syntax that the compiler knows, just like
int
or
for (... ) {}
in C. In Python 3 print is just a name, like len, say, in both py2 and py3.
A name on the module level is looked up first in the module's namespace, and
if it's not found in another special namespace that is built into the
interpreter:
>>> __builtins__
<module '__builtin__' (built-in)>
>>> __builtins__.len is len
True
The unqualified name "len" is the same object as __builtins__.len because it
is looked up there. When you overwrite it with your own name this will take
precedence:
>>> def len(x): return 42
...
>>> __builtins__.len is len
False
>>> len("abc")
42
OK that was probably a bad idea, let's remove our len() to see the built-in
again:
>>> del len
>>> len("abc")
3
The built-in namespace is user-writeable:
>>> __builtins__.spam = "ham"
>>> spam
'ham'
More information about the Tutor
mailing list