-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdump_and_load.py
More file actions
50 lines (40 loc) · 1.25 KB
/
dump_and_load.py
File metadata and controls
50 lines (40 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"""Basic example: dump a package to JSON and load it back."""
import json
import paker
# Create a simple module inline
modules = {
"greeting": {
"type": "module",
"extension": "py",
"code": (
"def hello(name):\n"
" return f'Hello, {name}!'\n"
"\n"
"def goodbye(name):\n"
" return f'Goodbye, {name}!'\n"
),
}
}
# Load from dict
with paker.loads(modules) as imp:
import greeting
print(greeting.hello("world"))
print(greeting.goodbye("world"))
# greeting is unloaded here
# Dump a real installed package to JSON file
# (requires 'requests' to be installed: pip install requests)
try:
with open("/tmp/requests_bundle.json", "w") as f:
paker.dump("requests", f, indent=2)
print(f"\nDumped requests to /tmp/requests_bundle.json")
# Load it back
import sys
for name in list(sys.modules):
if name.startswith("requests"):
del sys.modules[name]
with open("/tmp/requests_bundle.json", "r") as f:
with paker.load(f) as imp:
import requests
print(f"requests {requests.__version__} loaded from JSON")
except ImportError:
print("\nSkipping requests example (not installed)")