Is there a more Pythonic way to access to functions via their string name?










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'









share|improve this question
























  • You could have the derivatives as attributes of the original functions.

    – Matthieu Brucher
    Nov 13 '18 at 11:44















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'









share|improve this question
























  • You could have the derivatives as attributes of the original functions.

    – Matthieu Brucher
    Nov 13 '18 at 11:44













3












3








3


2






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'









share|improve this question
















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'






python function variables






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 '18 at 11:48







Basj

















asked Nov 13 '18 at 11:41









BasjBasj

6,00530105231




6,00530105231












  • You could have the derivatives as attributes of the original functions.

    – Matthieu Brucher
    Nov 13 '18 at 11:44

















  • You could have the derivatives as attributes of the original functions.

    – Matthieu Brucher
    Nov 13 '18 at 11:44
















You could have the derivatives as attributes of the original functions.

– Matthieu Brucher
Nov 13 '18 at 11:44





You could have the derivatives as attributes of the original functions.

– Matthieu Brucher
Nov 13 '18 at 11:44












2 Answers
2






active

oldest

votes


















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)>





share|improve this answer






























    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.






    share|improve this answer






















      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53280267%2fis-there-a-more-pythonic-way-to-access-to-functions-via-their-string-name%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      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)>





      share|improve this answer



























        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)>





        share|improve this answer

























          3












          3








          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)>





          share|improve this answer













          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)>






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 13 '18 at 11:54









          aydowaydow

          2,36011026




          2,36011026























              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.






              share|improve this answer



























                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.






                share|improve this answer

























                  5












                  5








                  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.






                  share|improve this answer













                  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.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 13 '18 at 11:47









                  jppjpp

                  100k2161111




                  100k2161111



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53280267%2fis-there-a-more-pythonic-way-to-access-to-functions-via-their-string-name%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Use pre created SQLite database for Android project in kotlin

                      Darth Vader #20

                      Ondo