Give function defaults arguments from a dictionary in Python

后端 未结 8 2306
予麋鹿
予麋鹿 2021-01-01 18:26

Let\'s imagine I have a dict :

d = {\'a\': 3, \'b\':4}

I want to create a function f that does the exact same thing than this function :

8条回答
  •  执念已碎
    2021-01-01 18:33

    Python is designed such that the local variables of any function can be determined unambiguously by looking at the source code of the function. So your proposed syntax

    def f(x, **d=d):
      print(x, a, b)
    

    is a nonstarter because there's nothing that indicates whether a and b are local to f or not; it depends on the runtime value of the dictionary, whose value could change across runs.

    If you can resign yourself to explicitly listing the names of all of your parameters, you can automatically set their default values at runtime; this has already been well covered in other answers. Listing the parameter names is probably good documentation anyway.

    If you really want to synthesize the whole parameter list at run time from the contents of d, you would have to build a string representation of the function definition and pass it to exec. This is how collections.namedtuple works, for example.

    Variables in module and class scopes are looked up dynamically, so this is technically valid:

    def f(x, **kwargs):
        class C:
            vars().update(kwargs)  # don't do this, please
            print(x, a, b)
    

    But please don't do it except in an IOPCC entry.

提交回复
热议问题