0

I want to create functions (def $name:) where name comes from array=['str1', 'str2', ...].

I tried the code above and already searched on stackoverflow and google but did not find any solution.

array = ['String1', 'String2', ...]

def array[0]:

     code1

def array[1]:
     code2

String1()
String2()
4
  • 1
    @Axium it's not impossible it's simply highly inadvisable Commented Aug 16, 2019 at 17:36
  • 1
    Don't do this. Python != PHP and doesn't give you any great way to create variable variables. Just use a container like a list or a dict. Commented Aug 16, 2019 at 17:37
  • in addition to the dupe target, you can (and should) store functions in any datastructure: [f1, f2] Commented Aug 16, 2019 at 17:38
  • Kind of a fun question though :). Commented Aug 16, 2019 at 17:50

1 Answer 1

0

You can't define a function using a variable. But it turns out that you can rebind functions variable names.

See this post: How to use a variable as function name in Python

Example of how to do that:

one = 'one'
two = 'two'
three = 'three'
l = [one, two, three]
def some_stuff():
    print("i am sure some stuff")
for item in l:
    def _f():
        some_stuff()
    globals()[item] = _f
    del _f

one()
two()
three()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.