Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dynamic function name
#1
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'
Reply
#2
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')
Output:
(3, 4) {'name': 'sample'}
Reply
#3
Sorry, I'm not getting it. Do you mean like?
decorator = lambda x: some_decorator
BTW, I don't have to call the function. I just have to define the function.

@some_decorator
def dynamic..():
  return 'somethin'
Reply
#4
(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.
Reply
#5
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'
Reply
#6
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Run function in parallel but inherite dynamic data from the previous function atizva 4 3,497 Jul-11-2018, 06:39 AM
Last Post: volcano63

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020