Created
April 18, 2022 07:47
-
-
Save autf/6ab9fc27ec2a8302b293b938eae011de to your computer and use it in GitHub Desktop.
This file contains 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
import dis, json, sys, inspect, base64 | |
bs = b'this is bytes' | |
plex = 1+2j | |
def code2dict(co): | |
d = {} | |
for k, v in inspect.getmembers(co): | |
# isbuildtin(x) -> Is x a built-in FUNCTION or METHOD? | |
if k.startswith('co_') and not inspect.isbuiltin(v): | |
d[k] = v | |
typed = lambda x: (x.__class__.__name__, x) | |
d['co_consts'] = tuple(map(typed, d['co_consts'])) | |
# d['co_consts'] = [(x.__class__.__name__, x) for x in d['co_consts']] | |
return d | |
class CodeEncoder(json.JSONEncoder): | |
def default(self, obj): | |
if isinstance(obj, bytes): | |
# b64encode(x) -> bytes | |
# bytes.decode() -> str | |
return base64.b64encode(obj).decode() | |
elif inspect.iscode(obj): | |
return code2dict(obj) | |
else: | |
return repr(obj) | |
# return json.JSONEncoder.default(self, obj) | |
co = compile(open(__file__).read(), __file__, 'exec') | |
json.dump(co, sys.stdout, cls=CodeEncoder) | |
# import rich.console | |
# print() | |
# rich.inspect(co) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment