Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 927
James Avatar asked Dec 06 '25 11:12

James


1 Answers

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.

like image 161
Martijn Pieters Avatar answered Dec 09 '25 00:12

Martijn Pieters



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!