hatmatrix
hatmatrix

Reputation: 44972

Best way to include functions defined by arbitrary user?

If a user is allowed to specify the syntax for both the function call and function itself, what is the best way to import the function? I use execfile in the current implementation, but is there a better way?

This is a strange application, but I want to facilitate access to libraries I've written through a python script that can be called from the command line. The user defines a simple syntax in a csv file, and can optionally define python functions which access functions from my library (mylibrary).

For instance here is the csv file contents ("userstrings.csv"):

x,"1"
y,"2"
z,"func({x},{y})"

Then, the user may define func in "userdefined.py":

def func(x,y):
    return mylibrary.add(x,y)

The main program would look something like this:

import csv
from collections import OrderedDict
import operator as mylibrary # this would be import mylibrary

execfile('userdefined.py')

class foo:

    def __init__(self,filename):
        with open(filename) as f:
            strings = [string for string in csv.reader(f)]
        self.strings = strings

    def execute(self):
        output = OrderedDict()
        for label, string in self.strings:
            output[label] = eval(string.format(**output))
        return output

bar = foo('userstrings.csv')

print bar.execute()

This would output

OrderedDict([('x', 1), ('y', 2), ('z', 3)])

To make a reproducible example, I just defined mylibrary to be the operator library above, but would normally be import mylibrary.

Is there a better way than invoking execfile to make the user defined function in such an application?

Upvotes: 1

Views: 29

Answers (1)

chepner
chepner

Reputation: 532508

Just import it.

try:
    import userdefined
except ImportError:
    pass

The user will just need to place the file in Python's search path, which you might augment from your script.

Upvotes: 1

Related Questions