1

I have a python script that starts with importing a python module that contains data. A very simplified example is given below:

my_data1.py

bar = 10
baz = [1, 5, 7]
...

my_func.py

from my_data1 import *
def foo():
 '''
 function that uses the things defined in data (scalar, list, dicts, etc.)
 in my_data
 '''
 return [bar] + baz

This works great for one set of data; however, I have my_data1.py, ..., my_data36.py.

my_data36.py

bar = 31
baz = [-1, 58, 8]
...

that I want to import and then run foo() with that data. I wanted to do something like this:

def foo(my_data):
 from my_data import *
results = []
for i in range(1,37):
 results.append(foo('my_data{}'.format(i)))

This doesn't work. Ideas?

gypaetus
7,4373 gold badges37 silver badges48 bronze badges
asked Feb 4, 2014 at 1:03
3
  • I could import the specific data from my_data if that makes it feasible, but I haven't been able to figure that out either. Commented Feb 4, 2014 at 1:04
  • Yes and no. Each of the 36 have the exact same data names with different values (i.e. my_data1 has bar= 3, my_data2 has bar=10 and foo() uses bar) Commented Feb 4, 2014 at 1:09
  • Why not get the "data" by reading and parsing a file? Commented Feb 4, 2014 at 2:05

2 Answers 2

2

Use __import__. It takes a string as parameter identifying the module to be imported, and returns the module, which then you can pass as an argument to your functions.

def processDataSet (module):
 print (module.baz)
for m in ['data1.py', 'data2.py', 'data69.py']:
 processDataSet (__import__ (m) )
answered Feb 4, 2014 at 1:47
Sign up to request clarification or add additional context in comments.

Comments

1

"from module import * is invalid inside function definitions." from http://docs.python.org/2/howto/doanddont.html#inside-function-definitions

answered Feb 4, 2014 at 1:51

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.