w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Overriding Python import without causing restricted execution mode

I did not get the RE error. From the python docs:

__import__: This function is invoked by the import statement. It can be replaced (by importing the __builtin__ module and assigning to __builtin__.__import__) in order to change semantics of the import statement

The following works for me (it does everything the same as the standard import, but replace spam with math.

>>> import builtins
>>> _import_alias = __import__
>>> builtins.__import__ = lambda module, *args, **kwargs:
_import_alias(module.replace("spam", "math"), *args, **kwargs)
>>> import spam as math
>>> math.factorial(10)

It is important that you create an alias of __import__ and that you override builtins.__import__, not the standard __import__.





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.