Python - overriding function parameters





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















Writing a cli function that should do the following:



In case, the function parameters are not set (I get them from docopt),
I would like to look them up from environment.
The following does not work due to fast loading in functions:



def my_function(a=None, b=None, c=None):
for v in ("a", "b", "c"):
if vars()[v] is None:
locals()[v] = getenv("env_{}".format(v).upper())
do_something_with(a, b, c)


What would be the pythonic way to achieve this?










share|improve this question





























    0















    Writing a cli function that should do the following:



    In case, the function parameters are not set (I get them from docopt),
    I would like to look them up from environment.
    The following does not work due to fast loading in functions:



    def my_function(a=None, b=None, c=None):
    for v in ("a", "b", "c"):
    if vars()[v] is None:
    locals()[v] = getenv("env_{}".format(v).upper())
    do_something_with(a, b, c)


    What would be the pythonic way to achieve this?










    share|improve this question

























      0












      0








      0








      Writing a cli function that should do the following:



      In case, the function parameters are not set (I get them from docopt),
      I would like to look them up from environment.
      The following does not work due to fast loading in functions:



      def my_function(a=None, b=None, c=None):
      for v in ("a", "b", "c"):
      if vars()[v] is None:
      locals()[v] = getenv("env_{}".format(v).upper())
      do_something_with(a, b, c)


      What would be the pythonic way to achieve this?










      share|improve this question














      Writing a cli function that should do the following:



      In case, the function parameters are not set (I get them from docopt),
      I would like to look them up from environment.
      The following does not work due to fast loading in functions:



      def my_function(a=None, b=None, c=None):
      for v in ("a", "b", "c"):
      if vars()[v] is None:
      locals()[v] = getenv("env_{}".format(v).upper())
      do_something_with(a, b, c)


      What would be the pythonic way to achieve this?







      python python-3.x






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 4 at 13:59









      ProfHase85ProfHase85

      7,36433648




      7,36433648
























          1 Answer
          1






          active

          oldest

          votes


















          1














          You can do this easily with keyword arguments:



          def my_function(**kwargs):
          for var in ('a', 'b', 'c'):
          if kwargs.get(var) is None:
          kwargs[var] = getenv("env_{}".format(v).upper())
          do_something_with(**kwargs)


          If you want to keep the signature, you can create a decorator (functools.wraps takes care of aligning the signatures):



          def defaults_from_env(function):
          @functools.wraps(function)
          def wrapper(**kwargs):
          for var in kwargs:
          if kwargs.get(var) is None:
          kwargs[var] = getenv("env_{}".format(var).upper())
          return function(**kwargs)
          return wrapper


          @defaults_from_env
          def my_function(a=None, b=None, c=None):
          print(a, b, c)


          However, this forces you to name all parameters when calling the decorated my_function (i.e. a=.., b=.., c=..). To avoid this, you could use inspect.signature to bind the parameters in the wrapper; this would allow you to get the name and value of all parameters, both *arg and **kwarg.






          share|improve this answer


























          • Thanks, thought about that. Unfortunately with kwargs I have no control over function params that are passed to the function and i would need to write: 1. a validator (to prevent parameters that are not allowed to be passed) 2. some extra parameter hinting for my ide, 3. I am not able to pass parameters by order

            – ProfHase85
            Jan 4 at 14:11












          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%2f54040405%2fpython-overriding-function-parameters%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          You can do this easily with keyword arguments:



          def my_function(**kwargs):
          for var in ('a', 'b', 'c'):
          if kwargs.get(var) is None:
          kwargs[var] = getenv("env_{}".format(v).upper())
          do_something_with(**kwargs)


          If you want to keep the signature, you can create a decorator (functools.wraps takes care of aligning the signatures):



          def defaults_from_env(function):
          @functools.wraps(function)
          def wrapper(**kwargs):
          for var in kwargs:
          if kwargs.get(var) is None:
          kwargs[var] = getenv("env_{}".format(var).upper())
          return function(**kwargs)
          return wrapper


          @defaults_from_env
          def my_function(a=None, b=None, c=None):
          print(a, b, c)


          However, this forces you to name all parameters when calling the decorated my_function (i.e. a=.., b=.., c=..). To avoid this, you could use inspect.signature to bind the parameters in the wrapper; this would allow you to get the name and value of all parameters, both *arg and **kwarg.






          share|improve this answer


























          • Thanks, thought about that. Unfortunately with kwargs I have no control over function params that are passed to the function and i would need to write: 1. a validator (to prevent parameters that are not allowed to be passed) 2. some extra parameter hinting for my ide, 3. I am not able to pass parameters by order

            – ProfHase85
            Jan 4 at 14:11
















          1














          You can do this easily with keyword arguments:



          def my_function(**kwargs):
          for var in ('a', 'b', 'c'):
          if kwargs.get(var) is None:
          kwargs[var] = getenv("env_{}".format(v).upper())
          do_something_with(**kwargs)


          If you want to keep the signature, you can create a decorator (functools.wraps takes care of aligning the signatures):



          def defaults_from_env(function):
          @functools.wraps(function)
          def wrapper(**kwargs):
          for var in kwargs:
          if kwargs.get(var) is None:
          kwargs[var] = getenv("env_{}".format(var).upper())
          return function(**kwargs)
          return wrapper


          @defaults_from_env
          def my_function(a=None, b=None, c=None):
          print(a, b, c)


          However, this forces you to name all parameters when calling the decorated my_function (i.e. a=.., b=.., c=..). To avoid this, you could use inspect.signature to bind the parameters in the wrapper; this would allow you to get the name and value of all parameters, both *arg and **kwarg.






          share|improve this answer


























          • Thanks, thought about that. Unfortunately with kwargs I have no control over function params that are passed to the function and i would need to write: 1. a validator (to prevent parameters that are not allowed to be passed) 2. some extra parameter hinting for my ide, 3. I am not able to pass parameters by order

            – ProfHase85
            Jan 4 at 14:11














          1












          1








          1







          You can do this easily with keyword arguments:



          def my_function(**kwargs):
          for var in ('a', 'b', 'c'):
          if kwargs.get(var) is None:
          kwargs[var] = getenv("env_{}".format(v).upper())
          do_something_with(**kwargs)


          If you want to keep the signature, you can create a decorator (functools.wraps takes care of aligning the signatures):



          def defaults_from_env(function):
          @functools.wraps(function)
          def wrapper(**kwargs):
          for var in kwargs:
          if kwargs.get(var) is None:
          kwargs[var] = getenv("env_{}".format(var).upper())
          return function(**kwargs)
          return wrapper


          @defaults_from_env
          def my_function(a=None, b=None, c=None):
          print(a, b, c)


          However, this forces you to name all parameters when calling the decorated my_function (i.e. a=.., b=.., c=..). To avoid this, you could use inspect.signature to bind the parameters in the wrapper; this would allow you to get the name and value of all parameters, both *arg and **kwarg.






          share|improve this answer















          You can do this easily with keyword arguments:



          def my_function(**kwargs):
          for var in ('a', 'b', 'c'):
          if kwargs.get(var) is None:
          kwargs[var] = getenv("env_{}".format(v).upper())
          do_something_with(**kwargs)


          If you want to keep the signature, you can create a decorator (functools.wraps takes care of aligning the signatures):



          def defaults_from_env(function):
          @functools.wraps(function)
          def wrapper(**kwargs):
          for var in kwargs:
          if kwargs.get(var) is None:
          kwargs[var] = getenv("env_{}".format(var).upper())
          return function(**kwargs)
          return wrapper


          @defaults_from_env
          def my_function(a=None, b=None, c=None):
          print(a, b, c)


          However, this forces you to name all parameters when calling the decorated my_function (i.e. a=.., b=.., c=..). To avoid this, you could use inspect.signature to bind the parameters in the wrapper; this would allow you to get the name and value of all parameters, both *arg and **kwarg.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 4 at 14:22

























          answered Jan 4 at 14:01









          BlackBearBlackBear

          15.5k83368




          15.5k83368













          • Thanks, thought about that. Unfortunately with kwargs I have no control over function params that are passed to the function and i would need to write: 1. a validator (to prevent parameters that are not allowed to be passed) 2. some extra parameter hinting for my ide, 3. I am not able to pass parameters by order

            – ProfHase85
            Jan 4 at 14:11



















          • Thanks, thought about that. Unfortunately with kwargs I have no control over function params that are passed to the function and i would need to write: 1. a validator (to prevent parameters that are not allowed to be passed) 2. some extra parameter hinting for my ide, 3. I am not able to pass parameters by order

            – ProfHase85
            Jan 4 at 14:11

















          Thanks, thought about that. Unfortunately with kwargs I have no control over function params that are passed to the function and i would need to write: 1. a validator (to prevent parameters that are not allowed to be passed) 2. some extra parameter hinting for my ide, 3. I am not able to pass parameters by order

          – ProfHase85
          Jan 4 at 14:11





          Thanks, thought about that. Unfortunately with kwargs I have no control over function params that are passed to the function and i would need to write: 1. a validator (to prevent parameters that are not allowed to be passed) 2. some extra parameter hinting for my ide, 3. I am not able to pass parameters by order

          – ProfHase85
          Jan 4 at 14:11




















          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%2f54040405%2fpython-overriding-function-parameters%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

          Mossoró

          Error while reading .h5 file using the rhdf5 package in R

          Pushsharp Apns notification error: 'InvalidToken'