1

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!

BenedictWilkins
  • 1,173
  • 8
  • 25

1 Answers1

3

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.

Omry Yadan
  • 31,280
  • 18
  • 64
  • 87
  • I added a simpler example for this that leverages the positional arguments support: https://github.com/facebookresearch/hydra/issues/1283#issuecomment-828956557 – Omry Yadan Apr 29 '21 at 05:49