Last active
January 12, 2021 11:58
-
-
Save kota7/186afafe75629853107b0a9562a29482 to your computer and use it in GitHub Desktop.
A way to hard-code a python object in a script using pickle dumps and loads
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
# This works when run as a script | |
# but not when copied to a notebook cell and run it. | |
import pickle | |
from collections import namedtuple | |
# We want to embed this object into a script | |
Foo = namedtuple("Foo", "a b") | |
a = Foo(1, 2) | |
obj = pickle.dumps(a) | |
with open("byte_embed_test_template.py") as f: | |
x = f.read() | |
x = x.replace("VALUEHERE", str(obj)) | |
with open("byte_embed_test.py", "wt") as f: | |
f.write(x) | |
print("*** Contents of byte_embed_test_template.py *********") | |
print("*****************************************************") | |
with open("byte_embed_test_template.py") as f: | |
print(f.read()) | |
print("*****************************************************") | |
print("*** Contents of byte_embed_test.py ******************") | |
print("*****************************************************") | |
with open("byte_embed_test.py") as f: | |
print(f.read()) | |
print("*****************************************************") | |
import byte_embed_test | |
print("*** Should print Foo(a=1, a=2) below ***") | |
byte_embed_test.func() | |
print("*** Should print 1 and 2 below ***") | |
print(byte_embed_test.y.a) | |
print(byte_embed_test.y.b) |
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 pickle | |
from collections import namedtuple | |
Foo = namedtuple("Foo", "a b") | |
x = 1 | |
y = pickle.loads(VALUEHERE) | |
def func(): | |
print(y) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment