Dynamically define functions with varying signature

2024/10/1 19:24:28

What I want to accomplish:

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 obviously clashing here between expanding a dict (what I want to do) and declaring a parameter that holds the keyword arguments (what I don't want to do).

Is this possible?

Answer

Based on my interpretation of your requirements -- you want to dynamically define a function with a signature that matches the content of adict provided at runtime -- there are two issues here which makes it impractical.

  1. If the arguments are defined at run-time, how can your function reference the variables? Are you planning to build the function body at run-time as well?
  2. dicts are unordered, so you cannot reliably use them to define positional arguments

I suspect this is an XY problem. If you can explain what you're trying to achieve then perhaps we can be of better help.

However, assuming you're trying to assign default keyword arguments using a dict then one way to achieve this would be to use decorators. For example:

def defaultArgs(default_kw):"decorator to assign default kwargs"def wrap(f):def wrapped_f(**kwargs):kw = {}kw.update(default_kw)  # apply defaultskw.update(kwargs)  # apply from input argsf(**kw)  # run actual function with updated kwargsreturn wrapped_freturn 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 will not be able to use positional arguments:

func(1, 2, 3)   # raises TypeError
https://en.xdnf.cn/q/70937.html

Related Q&A

python pandas plot with uneven timeseries index (with count evenly distributed)

My dataframe has uneven time index.how could I find a way to plot the data, and local the index automatically? I searched here, and I know I can plot something like e.plot()but the time index (x axis)…

python OpenAI gym monitor creates json files in the recording directory

I am implementing value iteration on the gym CartPole-v0 environment and would like to record the video of the agents actions in a video file. I have been trying to implement this using the Monitor wra…

Install xgboost under python with 32-bit msys failing

Trying to install xgboost is failing..? The version is Anaconda 2.1.0 (64-bit) on Windows & enterprise. How do I proceed? I have been using R it seems its quite easy to install new package in R …

Pythons _winapi module

I was trying to write some python code that requires calls to native WINAPI functions. At first I came across the pypiwin32 package. Then, somewhere on the internet I saw someone using the _winapi modu…

list comprehension with numpy arrays - bad practice?

I am wondering if the below approach would be considered bad practice, and if so, if someone could give some guidance towards another approach. Here is the code in question:a = np.array([[1,2,3],[4,5,6…

pandas: write dataframe to excel file *object* (not file)?

I have a dataframe that I want to convert to excel file, and return it using HTTP. Dataframes to_excel method accepts either a path, or an ExcelWriter, which, in turn, refers to a path.Is there any way…

win32: moving mouse with SetCursorPos vs. mouse_event

Is there any difference between moving the mouse in windows using the following two techniques?win32api.SetCursorPos((x,y))vs:nx = x*65535/win32api.GetSystemMetrics(0) ny = y*65535/win32api.GetSystemM…

Pandas: Unstacking One Column of a DataFrame

I want to unstack one column in my Pandas DataFrame. The DataFrame is indexed by the Date and I want to unstack the Country column so each Country is its own column. The current pandas DF looks like t…

python-polars split string column into many columns by delimiter

In pandas, the following code will split the string from col1 into many columns. is there a way to do this in polars? d = {col1: ["a/b/c/d", "a/b/c/d"]} df= pd.DataFrame(data=d) df…

pylint giving not-callable error for object property that is callable

Not sure if I am doing something wrong or if this is a problem with pylint. In the code below I get a linting error that self.type is not callable E1102.Although I could just ignore it and keep workin…