I have a string coming from the database. This string is the name of a file .py that is within a module. The structure is this:

files
├── file1.py
├── file2.py
└── __init__.py

The file1.py contain:

def file1(imprime):
    print(imprime)

The file2.py contain:

def file2(imprime):
    print(imprime)

I need to convert the string to a function that can be callable.

In main.py file I try:

import files
string = "file1.py"
b = getattr(file1, string)

text = 'print this...'

b(text)

Can anyone help me?

share|improve this question
1  
I dont understand the question ... also string is a terrible variable name :P – Joran Beasley yesterday
2  
Why not just do, import file1; b = file1.file1? – Kevin yesterday

2 Answers

There are a couple of problems. The string in this case shouldn't be ".py" file name but instead be a module or function name, so file1.

file1 isn't in scope though, because you've imported files, and file1 the function is inside files.file1 the module.

You could have files/init.py declare the following:

from file1 import *
from file2 import *

If you want the file1 function and the file2 function to exist on files. Then you would do b = getattr(files, string).

share|improve this answer

You can use the import function to import the module by name and stick that on the files module.

Edit: Changes to show how to call the function

import os
import files
wanted_file = "file1.py"
# name of module plus contained function
wanted_name = os.path.splitext(wanted_file)[0]
# if you do this many times, you can skip the import lookup after the first hit
if not hasattr(files, wanted_name):
    module = __import__('files.' + wanted_name)
    setattr(files, wanted_name, module)
else:
    module = getattr(files, wanted_name)
fctn = getattr(module, wanted_name)
text = 'print this...'
fctn(text)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.