Skip to content

Instantly share code, notes, and snippets.

@kota7
Last active January 12, 2021 11:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kota7/186afafe75629853107b0a9562a29482 to your computer and use it in GitHub Desktop.
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 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)
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