Search code examples
pythondecoratorfb-hydra

Re-referencing a large number of functions in python


I have a file functional.py which defines a number of useful functions. For each function, I want to create an alias that when called will give a reference to a function. Something like this:

foo/functional.py

def fun1(a):
    return a

def fun2(a):
    return a+1

...

foo/__init__.py


from inspect import getmembers, isfunction  
from . import functional

for (name, fun) in getmembers(functional, isfunction):
    dun = lambda f=fun: f
    globals()[name] = dun
>> bar.fun1()(1)
>> 1
>> bar.fun2()(1)
>> 2

I can get the functions from functional.py using inspect and dynamically define a new set of functions that are fit for my purpose.

But why? you might ask... I am using a configuration manager Hydra where one can instantiate objects by specifying the fully qualified name. I want to make use of the functions in functional.py in the config and have hydra pass a reference to the function when creating an object that uses the function (more details can be found in the Hydra documentation).

There are many functions and I don't want to write them all out ... people have pointed out in similar questions that modifying globals() for this purpose is bad practice. My use case is fairly constrained - documentation wise there is a one-one mapping (but obviously an IDE won't be able to resolve it).

Basically, I am wondering if there is a better way to do it!


Solution

  • Is your question related to this feature request and in particular to this comment?

    FYI: In Hydra 1.1, instantiate fully supports positional arguments so I think you should be able to call functools.partial directly without redefining it.