James Sapam
James Sapam

Reputation: 16940

Overwriting __builtins__ function not working with import

Here, is how i tried to overwrite __builtins__ function:

>>> lisa = __builtins__.list
>>> list('123')
['1', '2', '3']
>>>

And it works as i expect.

Now when i tried to overwrite import :

>>> importing = __builtins__.__import__
>>> importing sys
  File "<stdin>", line 1
    importing sys
            ^
SyntaxError: invalid syntax
>>> import sys
<module 'sys' (built-in)>
>>>

Why its not working when i tried to overwrite import ?

Upvotes: 3

Views: 167

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122142

You cannot create new keywords and statements in Python; import is a statement, importing is not.

All you did was bind the __import__ built-in function to a new name; you don't even need to use the __builtins__ module to do that:

importing = __import__

sys = importing('sys')

The __builtins__ name is a CPython implementation detail, and has nothing to do with keywords; it is the location Python looks up built-in functions, types and constants instead. Also see the __builtin__ module (no s).

To do what you want would require extending the Python parser, to recognize importing as an alias for import.

Upvotes: 3

Related Questions