0

I need to store a large numbers of functions rules in Python (around 100000 ), to be used after....

def rule1(x,y) :...
def rule2(x,y): ...

What is the best way to store, manage those function rules instance into Python structure ?

What about using Numpy dtype=np.object array ? (list are bad when they become too large...)

Main goal is to access in the fastest and minimum memory footprint when storing in memory.

Thanks

tensor
  • 3,088
  • 8
  • 37
  • 71

2 Answers2

2

Functions are first class objects in Python - you can store them just like you'd store any other variable or value:

def a():
  pass

def b():
  pass

funcs = [a,b]
funcs[0]() # calls `a()`.
g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
1

When you use those rules, you're going to have to reference them somehow. If your example is a hint of the naming convention, then go with a list. Calling them in sequence would be easy via map or in a loop.

rules = [rule1, rule2, ...]
for fn in rules:
    fn(arg1, arg2)  # this calls rule1 and rule2 with args (as an example)

If you may also reference them by name, then use a dict, like:

rules = {'rule1': rule1, 'rule2': rule2, ...}
something = rules['rule5'](arg1, arg2)
# or
for rule in rules:  # iterates over the dict's keys
    rules[rule](arg1, arg2)
aneroid
  • 12,983
  • 3
  • 36
  • 66