Created
June 14, 2023 22:03
-
-
Save Sigmanificient/fe15f43a70e6a9e52cb28dc4f5c602c8 to your computer and use it in GitHub Desktop.
Add a middleware to a builtin function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import wraps | |
def builtin_func_middleware(original): | |
import builtins | |
def wrapper(func): | |
@wraps(original) | |
def wrapped(*args, **kwargs): | |
if func(*args, **kwargs): | |
return original(*args, *kwargs) | |
raise ValueError("Middleware checked failed") | |
try: | |
setattr(builtins, original.__name__, wrapped) | |
except AttributeError: | |
print("Cannot override builtins", original.__name__) | |
return wrapped | |
return wrapper | |
BANNED_IMPORTS = ('inspect',) | |
@builtin_func_middleware(__import__) | |
def check_imports(*args, **kwargs): | |
name = args[0] if len(args) else kwargs.get("name") | |
if name is None: | |
return False | |
if name in BANNED_IMPORTS: | |
return False | |
return True | |
try: | |
import inspect | |
except ValueError: | |
print("Worked") | |
else: | |
print("failed :<") | |
print(__import__) | |
print(eval("__import__")) | |
print(breakpoint.__self__.__import__) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment