Getting the keyword arguments actually passed to a Python method

前端 未结 8 662
挽巷
挽巷 2020-12-24 03:45

I\'m dreaming of a Python method with explicit keyword args:

def func(a=None, b=None, c=None):
    for arg, val in magic_arg_dict.items():   # Where do I get         


        
相关标签:
8条回答
  • 2020-12-24 04:11

    Magic is not the answer:

    def funky(a=None, b=None, c=None):
        for name, value in [('a', a), ('b', b), ('c', c)]:
            print name, value
    
    0 讨论(0)
  • 2020-12-24 04:13

    Here is the easiest and simplest way:

    def func(a=None, b=None, c=None):
        args = locals().copy()
        print args
    
    func(2, "egg")
    

    This give the output: {'a': 2, 'c': None, 'b': 'egg'}. The reason args should be a copy of the locals dictionary is that dictionaries are mutable, so if you created any local variables in this function args would contain all of the local variables and their values, not just the arguments.

    More documentation on the built-in locals function here.

    0 讨论(0)
提交回复
热议问题