简体   繁体   中英

How to import a function that you do not know the names of in python?

So, I am trying to import a function, from a specific file, and run it, in a function on a different file. Here is my code:

import re

def get_func_names(string):
    temp = re.compile(r"def [a-z]+")
    result = temp.findall(string)
    return [elem[4:] for elem in result]

def test_a_function(val):
    import swift
    g = open('swift.py', 'r')
    g = g.read()
    functions = get_func_names(g)
    k = functions[0]
    k = eval(k(val))
    return k

get_func_names uses the re module and pattern matching to get all the names that appear after 'def' in a python document, and only returns the names of the functions. test_a_function imports the python document, opens it, applies get_func_names, and tries to evaluate the first string of a function name using the eval function, but i get an error saying the 'str' object is not callable.

Is there a way to fix my method or another way to do this?

EDIT:

Ok thank you for the answer, but in the end for some reason, it would only work with the importlib module

import importlib
import types

def getfuncs(modulename):
    retval = {}
    opened = importlib.import_module(modulename)
    for name in opened.__dict__.keys():
        if isinstance(opened.__dict__[name], types.FunctionType):
            retval[name] = opened.__dict__[name]
    return retval

Consider:

import types

def getfuncs(modulename):
    retval = {}
    module = __import__(modulename, globals(), locals(), [], -1)
    for (name, item) in module.__dict__.iteritems():
        if isinstance(item, types.FunctionType):
            retval[name] = item
    return retval

getfuncs('swift') # returns a dictionary of functions in the swift module

If you don't want side effects from evaluation occurring at the module level you could use the AST module to only evaluate function definitions, but this would be considerably more work (and modules written not expecting this behavior would not necessarily function correctly).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM