I wish there was a pattern to encapsulate data and functions from a module.
So you could do:
import greeter
greet1 = encapsulate(greeter)
greet2 = encapsulate(greeter)
greet1.name = 'Joe'
greet2.name = 'Sue'
greet1.greet()
greet2.greet()
And greeter.py would look like this: name = 'nobody'
def greet():
print ('Hello '+name)
Output: Hello Joe
Hello Sue
This would be so much nicer and leaner than classes.Here's my attempt:
~/Code/local/hn ································ at 09:14:14
python3 hn_example.py
Hello Joe
Hello Sue
~/Code/local/hn ································ at 09:14:16
cat hn_example.py greeter.py
───────┬───────────────────────────────────────────────────────────
│ File: hn_example.py
───────┼───────────────────────────────────────────────────────────
1 │ import sys
2 │ from importlib.util import find_spec, module_from_spec
3 │
4 │ def encapsulate(mod):
5 │ s = find_spec(mod)
6 │ m = module_from_spec(s)
7 │ s.loader.exec_module(m)
8 │ return m
9 │
10 │ greet1 = encapsulate("greeter")
11 │ greet2 = encapsulate("greeter")
12 │
13 │ greet1.name = 'Joe'
14 │ greet2.name = 'Sue'
15 │
16 │ greet1.greet()
17 │ greet2.greet()
───────┴───────────────────────────────────────────────────────────
───────┬───────────────────────────────────────────────────────────
│ File: greeter.py
───────┼───────────────────────────────────────────────────────────
1 │ name = 'nobody'
2 │
3 │ def greet():
4 │ print ('Hello '+name)
───────┴───────────────────────────────────────────────────────────
I differ from your syntax by passing string parameters on (your) line 3 & 4 (my line 10 & 11).I think this isn't a good idea though, i'd lookup __slots__ if leanness is an issue.
What species of cat is that?
It looks like bat https://github.com/sharkdp/bat