0

My project layout looks like:

run.py
jobs/
   job1.py
   job2.py

job1.py is pretty basic:

class job1():

    def __init__(self):
        print 'yo'

In run.py, I have:

name = 'job1'
classname = 'jobs.%s' % name
__import__(classname)

Which obviously does not work:

Traceback (most recent call last):
  File "run.py", line 5, in <module>
    __import__(classname)
ImportError: No module named jobs.job1

What is the best way to import the modules in this manner?

Wells
  • 10,415
  • 14
  • 55
  • 85
  • Why? do you "really" want to do imports like this? – Jakob Bowyer Jun 20 '12 at 17:37
  • So I can easily add the modules by putting their classes in the `jobs` directory. – Wells Jun 20 '12 at 17:38
  • This is very similar to [Dynamic module import in Python](http://stackoverflow.com/questions/301134/dynamic-module-import-in-python). And as [Ashwini Chaudhary](http://stackoverflow.com/questions/11125074/python-importing-modules-in-project-using-dynamic-naming#11125112) explains below, you are probably simply missing an `__init__.py` file in your jobs folder to make it a package. – Rodrigue Jun 20 '12 at 17:51

2 Answers2

2

first of all create a __init__.py file inside jobs folder, to make this jobs.jobs1 thing work.

Chinmay Kanchi
  • 62,729
  • 22
  • 87
  • 114
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
1

Add this to your __init__.py in jobs directory

import os
jobs = {}
for module in (name for name in os.listdir(".") if name.endswith(".py")):
    jobs[module] = __import__(module)

Then just use it like this

from jobs import jobs
Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91