How to use a variable as a function name in Python

Is it possible to use a variable as a function name in python? For instance:

list = [one, two, three]
for item in list:
    def item():
         some_stuff()
+4
source share
8 answers

Functions in Python are objects that have a name that refers to them, so you can pass them in, store them in lists and dictionaries (usually used when creating jump tables).

those. it works:

   def one():
        print "1"

    def two():
        print "2"

    def three():
        print "3"

    l = [one, two, three]

    for item in l:
        item()

It will be printed:

1
2
3

Do not use listas a variable name, because in this way you override buildin.

defis a statement that also executes, unlike defenitions in compiled languages. Therefore, when you call def item():, you do not specify a function one, two, threebut the name of the override item.

, , . , , , .

+7

, , . , .

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()
+5

- . , . , . python , :

>name=1
>name
1
>def name(x): print(x+1)

>name
function name at 0x000001CE8B8122F0
+1

:

from types import FunctionType
from copy import copy

def copy_function(fn):
    return FunctionType(copy(fn.func_code), copy(fn.func_globals), name=item,
                        argdefs=copy(fn.func_defaults),
                        closure=copy(fn.func_closure))

list = ['one', 'two', 'three']

for item in list:
    def _fn():
        print(item)
    globals()[item] = copy_function(_fn)
list = map(eval, list)
+1

, ,

list = ['one', 'two', 'three'] for item in list: item() def item(): print list

: 'string'

0

:

funcs = ["one", "two", "three"]
for item in funcs:
    def bindedfunc():
         # function stuff there
    exec("{} = bindedfunc".format(item))

one()
two()
three()

, one, two three ( ).

PS: , , .

0

globals():

globals()['use_variable_as_function_name']()

use_variable_as_function_name()

: https://bytes.com/topic/python/answers/792283-calling-variable-function-name


, ( ): URL- :

l = ['condition1', 'condition2', 'condition3']

if 'condition1.' in href:
    return do_something_condition1()
if 'condition2.' in href:
    return do_something_condition2()
if 'condition3.' in href:
    return do_something_condition3()

- 19 .

, , .

:

for e in l:              # this is my condition list
    if e + '.' in href:  # this is the mechanism to choose the right function
        return globals()['do_something_' + e]()

, , .

, , , , URL:

def do_something_condition1(href):
    # special code 1
    print('========1=======' + href)

def do_something_condition2(href):
    # special code 2
    print('========2=======' + href)

def do_something_condition3(href):
    # special code 3
    print('========3=======' + href)

:

>>> href = 'https://google.com'
>>> for e in l:
...     globals()['do_something_' + e](href)
...
========1=======https://google.com
========2=======https://google.com
========3=======https://google.com

, :

success = '________processed successfully___________ ' 

def do_something_google(href):
    # special code 1
    print('========we do google-specific stuff=======')
    return success + href 

def do_something_bing(href):
    # special code 2
    print('========we do bing-specific stuff=======')
    return success + href 

def do_something_wikipedia(href):
    # special code 3
    print('========we do wikipedia-specific stuff=======')
    return success + href 

:

l = ['google', 'bing', 'wikipedia']

href = 'https://google.com'

def test(href):
    for e in l:
        if e + '.' in href:
            return globals()['do_something_' + e](href)

>>> test(href)
========we do google-specific stuff=======
'________processed successfully___________ https://google.com'

:

, . .

0

Here is a workaround wrapped in class. It uses a dictionary to display:

class function_class:
    def __init__(self,fCase):
        fDic = {'A':self.A,         # mapping: string --> variable = function name
                'B':self.B,
                'C':self.C}
        self.fActive = fDic[fCase]
    def A(self): print('here runs function A')
    def B(self): print('here runs function B')
    def C(self): print('here runs function C')
    def run_function(self):
        self.fActive()

#---- main ----------        
fList = ['A','B','C']              # list with the function names as strings
for f in fList:                    # run through the list
    g = function_class(f)
    g.run_function()

Output:

here runs function A
here runs function B
here runs function C
0
source

Source: https://habr.com/ru/post/1695705/


All Articles