If my code uses third party modules that cannot be trusted, is there anything to prevent situation like this:
UntrustedModule.py:
import random
random.random = lambda : 4
MyModule.py:
import random
import UntrustedModule
print (random.random())
where just importing this module breaks assumptions about other, unrelated ones?
No, you can't have any such guarantee in Python, at least not in the CPython implementation. When you import a module its code is run, and it has full access to every part of the interpreter (and likely big parts of your system). No way to avoid this. It is unwise to ever load untrusted code, because there is so much it can do.
However you may be interested in running the process in an isolated process, and only communicate with it by IPC. This is a huge topic and it depends on the degree of isolation you need and how much you trust the external code.
PyPy implements some sandboxing features. It's not as simple as just "turning sandboxing on" but it's one of many ways to isolate untrusted code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With