Dynamically identify functions with different signatures

What I want to do:

dct = {'foo':0, 'bar':1, 'baz':2} def func(**dct): pass #function signature is now func(foo=0, bar=1, baz=2) 

However, the ** syntax is clearly confronted here between the dict extension (what I want to do) and the declaration of a parameter containing the keyword arguments (which I don't want to do).

Is it possible?

+4
source share
3 answers

Based on my interpretation of your requirements - you want to dynamically define a function with a signature that matches the contents of the dict provided at runtime, there are two problems that make it impractical.

  • If arguments are defined at runtime, how can your function refer to variables? Are you also planning to create a function body at runtime?
  • dict are unordered, so you cannot reliably use them to determine positional arguments

I suspect this is an XY problem. If you can explain what you are trying to achieve, perhaps we can help.

However , provided you are trying to assign default keyword arguments using dict , one way to achieve this would be to use decorators . For instance:

 def defaultArgs(default_kw): "decorator to assign default kwargs" def wrap(f): def wrapped_f(**kwargs): kw = {} kw.update(default_kw) # apply defaults kw.update(kwargs) # apply from input args f(**kw) # run actual function with updated kwargs return wrapped_f return wrap 

You can then use this decorator to assign default keyword arguments to a function that expects only keyword arguments:

 defaults = {'foo':0, 'bar':1, 'baz':2} @defaultArgs(defaults) def func(**kwargs): print kwargs # args accessible via the kwargs dict 

Results:

 func() # prints {'baz': 2, 'foo': 0, 'bar': 1} func(foo=2) # prints {'baz': 2, 'foo': 2, 'bar': 1} params = {'bar':1000, 'hello':'world'} func(**params) # prints {'baz': 2, 'foo': 0, 'bar': 1000, 'hello': 'world'} 

Note that you cannot use positional arguments:

 func(1, 2, 3) # raises TypeError 
+5
source

what do you want, i believe that eval() link

The answer I gave on a similar question: fooobar.com/questions/1428565 / ...

0
source

I'm really not sure what you plan to accomplish here. The following works (view):

 def func(**dct): pass dct = {'foo':0, 'bar':1, 'baz':2} func(**dct) 

How do you plan to use foo , bar or baz in a function if they are created dynamically? If you give more details about what you are actually trying to accomplish, we might be a little more helpful.

0
source

All Articles