Dynamic function name - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Dynamic function name (/thread-19701.html) |
Dynamic function name - bhojendra - Jul-11-2019 I have to use dynamic function name which is defined after some decorator: @some_decorator def dynamic(): return 'somethin'Something like: some_var = 'value' @some_decorator def f'dynamic_{some_var}'(): # syntax error, but if it was available, would have been a nice feature return 'somethin' RE: Dynamic function name - scidam - Jul-11-2019 You can do something like this: def create_func(name): def myfunc(*args, **kwargs): print(args, kwargs) # write function content here return myfunc func_name = 'mys' decorator = lambda x: x # entity decorator globals()[func_name] = decorator(create_func(func_name)) mys(3,4, name='sample')
RE: Dynamic function name - bhojendra - Jul-11-2019 Sorry, I'm not getting it. Do you mean like? decorator = lambda x: some_decoratorBTW, I don't have to call the function. I just have to define the function. @some_decorator def dynamic..(): return 'somethin' RE: Dynamic function name - scidam - Jul-11-2019 (Jul-11-2019, 07:18 AM)bhojendra Wrote: Sorry, I'm not getting it. Do you mean like?Just use some_decorator instead of decorator .
RE: Dynamic function name - bhojendra - Jul-11-2019 Ah, yeah. I meant that. But didn't work for me. It's actually like: decorator = lambda x: some_decorator.some_method()I expected it work. But it din't. Also, tried: some_decorator = lambda x: x.some_method()Where, my actual function definition is like: @some_decorator.some_method() def dynamic(): return 'somethin' RE: Dynamic function name - scidam - Jul-12-2019 If your some_decorator function is already defined, you don't need to use the lambda at all. Drop line # 8 in my code above and just use some_decorator instead of decorator .
|