Method that takes a method as a parameter with an optional parameter









up vote
1
down vote

favorite












I have two methods from a library that work in the same manner. The difference is that one takes an additional, optional parameter. For example:



def method1(a, b, c):
...

def method2(a, b, c, d=None):
...


I have to perform the same task on the results of these methods, so I have a method that combines them that looks like this:



def wrapper(method, a, b, c, d=None):

...

if d:
results = method(a, b, c, d=d)
else:
results = method(a, b, c)

...


This works, but as I add more methods that have different optional arguments it becomes cumbersome. Is there a way a better way to handle these parameters?










share|improve this question

















  • 2




    Look at the * operator for function arguments; I suspect you can solve your problem from there with a simple list of arguments, such as results = method(*arg_list)
    – Prune
    Nov 9 at 17:51










  • try **kwargs for the parameter d.
    – Naveen
    Nov 9 at 17:52










  • Are these methods or functions? But I agree, probably best if you modify the methods/functions to handle the args/kwargs conditionally.
    – Idlehands
    Nov 9 at 18:33










  • In my case, method 1 and 2 are actually methods and the wrapper is a function, but I was trying to generalize for this example. I didn't realize *args as a whole could be passed through.
    – billypilgrim
    Nov 10 at 17:23















up vote
1
down vote

favorite












I have two methods from a library that work in the same manner. The difference is that one takes an additional, optional parameter. For example:



def method1(a, b, c):
...

def method2(a, b, c, d=None):
...


I have to perform the same task on the results of these methods, so I have a method that combines them that looks like this:



def wrapper(method, a, b, c, d=None):

...

if d:
results = method(a, b, c, d=d)
else:
results = method(a, b, c)

...


This works, but as I add more methods that have different optional arguments it becomes cumbersome. Is there a way a better way to handle these parameters?










share|improve this question

















  • 2




    Look at the * operator for function arguments; I suspect you can solve your problem from there with a simple list of arguments, such as results = method(*arg_list)
    – Prune
    Nov 9 at 17:51










  • try **kwargs for the parameter d.
    – Naveen
    Nov 9 at 17:52










  • Are these methods or functions? But I agree, probably best if you modify the methods/functions to handle the args/kwargs conditionally.
    – Idlehands
    Nov 9 at 18:33










  • In my case, method 1 and 2 are actually methods and the wrapper is a function, but I was trying to generalize for this example. I didn't realize *args as a whole could be passed through.
    – billypilgrim
    Nov 10 at 17:23













up vote
1
down vote

favorite









up vote
1
down vote

favorite











I have two methods from a library that work in the same manner. The difference is that one takes an additional, optional parameter. For example:



def method1(a, b, c):
...

def method2(a, b, c, d=None):
...


I have to perform the same task on the results of these methods, so I have a method that combines them that looks like this:



def wrapper(method, a, b, c, d=None):

...

if d:
results = method(a, b, c, d=d)
else:
results = method(a, b, c)

...


This works, but as I add more methods that have different optional arguments it becomes cumbersome. Is there a way a better way to handle these parameters?










share|improve this question













I have two methods from a library that work in the same manner. The difference is that one takes an additional, optional parameter. For example:



def method1(a, b, c):
...

def method2(a, b, c, d=None):
...


I have to perform the same task on the results of these methods, so I have a method that combines them that looks like this:



def wrapper(method, a, b, c, d=None):

...

if d:
results = method(a, b, c, d=d)
else:
results = method(a, b, c)

...


This works, but as I add more methods that have different optional arguments it becomes cumbersome. Is there a way a better way to handle these parameters?







python methods optional-parameters






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 9 at 17:47









billypilgrim

456




456







  • 2




    Look at the * operator for function arguments; I suspect you can solve your problem from there with a simple list of arguments, such as results = method(*arg_list)
    – Prune
    Nov 9 at 17:51










  • try **kwargs for the parameter d.
    – Naveen
    Nov 9 at 17:52










  • Are these methods or functions? But I agree, probably best if you modify the methods/functions to handle the args/kwargs conditionally.
    – Idlehands
    Nov 9 at 18:33










  • In my case, method 1 and 2 are actually methods and the wrapper is a function, but I was trying to generalize for this example. I didn't realize *args as a whole could be passed through.
    – billypilgrim
    Nov 10 at 17:23













  • 2




    Look at the * operator for function arguments; I suspect you can solve your problem from there with a simple list of arguments, such as results = method(*arg_list)
    – Prune
    Nov 9 at 17:51










  • try **kwargs for the parameter d.
    – Naveen
    Nov 9 at 17:52










  • Are these methods or functions? But I agree, probably best if you modify the methods/functions to handle the args/kwargs conditionally.
    – Idlehands
    Nov 9 at 18:33










  • In my case, method 1 and 2 are actually methods and the wrapper is a function, but I was trying to generalize for this example. I didn't realize *args as a whole could be passed through.
    – billypilgrim
    Nov 10 at 17:23








2




2




Look at the * operator for function arguments; I suspect you can solve your problem from there with a simple list of arguments, such as results = method(*arg_list)
– Prune
Nov 9 at 17:51




Look at the * operator for function arguments; I suspect you can solve your problem from there with a simple list of arguments, such as results = method(*arg_list)
– Prune
Nov 9 at 17:51












try **kwargs for the parameter d.
– Naveen
Nov 9 at 17:52




try **kwargs for the parameter d.
– Naveen
Nov 9 at 17:52












Are these methods or functions? But I agree, probably best if you modify the methods/functions to handle the args/kwargs conditionally.
– Idlehands
Nov 9 at 18:33




Are these methods or functions? But I agree, probably best if you modify the methods/functions to handle the args/kwargs conditionally.
– Idlehands
Nov 9 at 18:33












In my case, method 1 and 2 are actually methods and the wrapper is a function, but I was trying to generalize for this example. I didn't realize *args as a whole could be passed through.
– billypilgrim
Nov 10 at 17:23





In my case, method 1 and 2 are actually methods and the wrapper is a function, but I was trying to generalize for this example. I didn't realize *args as a whole could be passed through.
– billypilgrim
Nov 10 at 17:23













2 Answers
2






active

oldest

votes

















up vote
1
down vote













Here is some code that might accomplish what you're looking for.



You can pass a collection of methods into wrapper and that function will return the value of any method that has key word arguments mapped to kwargs.



def method1(a, b, c):
return a, b, c


def method2(a, b, c, d=None):
return a, b, c, d

methods = (
method1,
method2,
) # Collection of methods to run.

def wrapper(kwargs, methods=methods):
"""Loop over methods with kwargs."""
for method in methods:
try: # Call method with **kwargs
return method(**kwargs) # Return value if keys in kwargs fit signature of method.
except TypeError as err: # Handle error if keyword args don't match.
print(f'err "err" for method "method')

kwargs_collection = (dict(zip(args, (f'value for arg: "arg"' for arg in args)))
for args in ('abcd', 'abc', ))




for test_kwargs in kwargs_collection:
print(wrapper(test_kwargs))


OUTPUT:




err "method1() got an unexpected keyword argument 'd'" for method "function method1 at 0x7f900c2b7d90"



('value for arg: "a"', 'value for arg: "b"', 'value for arg: "c"', 'value for arg: "d"')



('value for arg: "a"', 'value for arg: "b"', 'value for arg: "c"')







share|improve this answer





























    up vote
    0
    down vote













    For the wrapper function, I decided to just do something like the following as suggested in the comments:



    def wrapper(method, *args):

    ...

    results = method(*args)

    ...


    Error handling should be incorporated to make sure the proper arguments are being passed as well, as suggested in another answer.






    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',
      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%2f53230895%2fmethod-that-takes-a-method-as-a-parameter-with-an-optional-parameter%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








      up vote
      1
      down vote













      Here is some code that might accomplish what you're looking for.



      You can pass a collection of methods into wrapper and that function will return the value of any method that has key word arguments mapped to kwargs.



      def method1(a, b, c):
      return a, b, c


      def method2(a, b, c, d=None):
      return a, b, c, d

      methods = (
      method1,
      method2,
      ) # Collection of methods to run.

      def wrapper(kwargs, methods=methods):
      """Loop over methods with kwargs."""
      for method in methods:
      try: # Call method with **kwargs
      return method(**kwargs) # Return value if keys in kwargs fit signature of method.
      except TypeError as err: # Handle error if keyword args don't match.
      print(f'err "err" for method "method')

      kwargs_collection = (dict(zip(args, (f'value for arg: "arg"' for arg in args)))
      for args in ('abcd', 'abc', ))




      for test_kwargs in kwargs_collection:
      print(wrapper(test_kwargs))


      OUTPUT:




      err "method1() got an unexpected keyword argument 'd'" for method "function method1 at 0x7f900c2b7d90"



      ('value for arg: "a"', 'value for arg: "b"', 'value for arg: "c"', 'value for arg: "d"')



      ('value for arg: "a"', 'value for arg: "b"', 'value for arg: "c"')







      share|improve this answer


























        up vote
        1
        down vote













        Here is some code that might accomplish what you're looking for.



        You can pass a collection of methods into wrapper and that function will return the value of any method that has key word arguments mapped to kwargs.



        def method1(a, b, c):
        return a, b, c


        def method2(a, b, c, d=None):
        return a, b, c, d

        methods = (
        method1,
        method2,
        ) # Collection of methods to run.

        def wrapper(kwargs, methods=methods):
        """Loop over methods with kwargs."""
        for method in methods:
        try: # Call method with **kwargs
        return method(**kwargs) # Return value if keys in kwargs fit signature of method.
        except TypeError as err: # Handle error if keyword args don't match.
        print(f'err "err" for method "method')

        kwargs_collection = (dict(zip(args, (f'value for arg: "arg"' for arg in args)))
        for args in ('abcd', 'abc', ))




        for test_kwargs in kwargs_collection:
        print(wrapper(test_kwargs))


        OUTPUT:




        err "method1() got an unexpected keyword argument 'd'" for method "function method1 at 0x7f900c2b7d90"



        ('value for arg: "a"', 'value for arg: "b"', 'value for arg: "c"', 'value for arg: "d"')



        ('value for arg: "a"', 'value for arg: "b"', 'value for arg: "c"')







        share|improve this answer
























          up vote
          1
          down vote










          up vote
          1
          down vote









          Here is some code that might accomplish what you're looking for.



          You can pass a collection of methods into wrapper and that function will return the value of any method that has key word arguments mapped to kwargs.



          def method1(a, b, c):
          return a, b, c


          def method2(a, b, c, d=None):
          return a, b, c, d

          methods = (
          method1,
          method2,
          ) # Collection of methods to run.

          def wrapper(kwargs, methods=methods):
          """Loop over methods with kwargs."""
          for method in methods:
          try: # Call method with **kwargs
          return method(**kwargs) # Return value if keys in kwargs fit signature of method.
          except TypeError as err: # Handle error if keyword args don't match.
          print(f'err "err" for method "method')

          kwargs_collection = (dict(zip(args, (f'value for arg: "arg"' for arg in args)))
          for args in ('abcd', 'abc', ))




          for test_kwargs in kwargs_collection:
          print(wrapper(test_kwargs))


          OUTPUT:




          err "method1() got an unexpected keyword argument 'd'" for method "function method1 at 0x7f900c2b7d90"



          ('value for arg: "a"', 'value for arg: "b"', 'value for arg: "c"', 'value for arg: "d"')



          ('value for arg: "a"', 'value for arg: "b"', 'value for arg: "c"')







          share|improve this answer














          Here is some code that might accomplish what you're looking for.



          You can pass a collection of methods into wrapper and that function will return the value of any method that has key word arguments mapped to kwargs.



          def method1(a, b, c):
          return a, b, c


          def method2(a, b, c, d=None):
          return a, b, c, d

          methods = (
          method1,
          method2,
          ) # Collection of methods to run.

          def wrapper(kwargs, methods=methods):
          """Loop over methods with kwargs."""
          for method in methods:
          try: # Call method with **kwargs
          return method(**kwargs) # Return value if keys in kwargs fit signature of method.
          except TypeError as err: # Handle error if keyword args don't match.
          print(f'err "err" for method "method')

          kwargs_collection = (dict(zip(args, (f'value for arg: "arg"' for arg in args)))
          for args in ('abcd', 'abc', ))




          for test_kwargs in kwargs_collection:
          print(wrapper(test_kwargs))


          OUTPUT:




          err "method1() got an unexpected keyword argument 'd'" for method "function method1 at 0x7f900c2b7d90"



          ('value for arg: "a"', 'value for arg: "b"', 'value for arg: "c"', 'value for arg: "d"')



          ('value for arg: "a"', 'value for arg: "b"', 'value for arg: "c"')








          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 10 at 16:58

























          answered Nov 9 at 18:55









          DMfll

          88811828




          88811828






















              up vote
              0
              down vote













              For the wrapper function, I decided to just do something like the following as suggested in the comments:



              def wrapper(method, *args):

              ...

              results = method(*args)

              ...


              Error handling should be incorporated to make sure the proper arguments are being passed as well, as suggested in another answer.






              share|improve this answer
























                up vote
                0
                down vote













                For the wrapper function, I decided to just do something like the following as suggested in the comments:



                def wrapper(method, *args):

                ...

                results = method(*args)

                ...


                Error handling should be incorporated to make sure the proper arguments are being passed as well, as suggested in another answer.






                share|improve this answer






















                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  For the wrapper function, I decided to just do something like the following as suggested in the comments:



                  def wrapper(method, *args):

                  ...

                  results = method(*args)

                  ...


                  Error handling should be incorporated to make sure the proper arguments are being passed as well, as suggested in another answer.






                  share|improve this answer












                  For the wrapper function, I decided to just do something like the following as suggested in the comments:



                  def wrapper(method, *args):

                  ...

                  results = method(*args)

                  ...


                  Error handling should be incorporated to make sure the proper arguments are being passed as well, as suggested in another answer.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 10 at 17:18









                  billypilgrim

                  456




                  456



























                       

                      draft saved


                      draft discarded















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53230895%2fmethod-that-takes-a-method-as-a-parameter-with-an-optional-parameter%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