3

I have a few functions (hardcoded, I don't want Python to compute the derivatives, in reality the functions are more complex):

def f(x): return x
def g(x): return x ** 2
def f_prime(x): return 1
def g_prime(x): return 2 * x

and a list a functions:

myfunctions = [f, f, g, f]

How to get the list of the related "prime" functions?

I was thinking about:

myderivatives = [globals()[function.__name__ + '_prime'] for function in myfunctions]

and it works:

[<function f_prime at 0x00000000022CF048>, <function f_prime at 0x00000000022CF048>, <function g_prime at 0x00000000022CF0B8>, <function f_prime at 0x00000000022CF048>]

but is there a more Pythonic way to get the list of the "prime" functions associated to the original versions?


Also there is a corner case:

from module1 import thisfunction as f
def f_prime(x): 
    pass

globals()[f.__name__ + '_prime']  
# doesn't work because f.__name__ + '_prime' is 'thisfunction_prime' and not 'f_prime'
1
  • You could have the derivatives as attributes of the original functions. Commented Nov 13, 2018 at 11:44

2 Answers 2

5

Define a dictionary to hold your functions and then use a list comprehension:

funcd = {'f': f, 'g': g, 'f_prime': f_prime, 'g_prime': g_prime}

myderivatives = [func for name, func in funcd.items() if name.endswith('_prime')]

The benefit of this solution is it defines precisely the scope of functions you wish to filter. Use of globals is not recommended, and very rarely necessary.

Sign up to request clarification or add additional context in comments.

Comments

3

Following on from jpp's answer you could arrange the functions in a dict mapping from function to derivative like so

In [64]: primes = {f: f_prime, g: g_prime}

In [65]: primes.values()
Out[65]: dict_values([<function g_prime at 0x7f3594174c80>, <function f_prime at 0x7f3594174a60>])

In [66]: primes[f]
Out[66]: <function __main__.f_prime(x)>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.