2

I have this structure:

project/
    sources/
        __init__.py
        source_one.py
        source_teo.py
    main.py

Then in main.py

import sources

# Here I'd like to get a list with [source_one, source_two]

Then import them dinamycally.

Is there any way to get this?

EDIT

What I get from dir(sources):

if I do import sources I get ['__author__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']

If I do from sources import * I get ['__author__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']

If I do from sources import source_one I get ['__author__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'source_one']

But, I don't know the name of files in sources package, this is only an example. How can I find them?

Community
  • 1
  • 1
Gocht
  • 9,924
  • 3
  • 42
  • 81

2 Answers2

1

you should import relative to the current file location

Example :

  1. from sources.source_one import ClassSourceOne
  2. from sources import *

    In example 2, you can call the classes only by name_of_module.ClassName

Or you can use dynamicly import as shown here : import dynamicly from package

Also I recommend to import only the classes/modules you use that's why I recommend

from module import Class 

And not using import * so it import all the module dependencies too

Gefen Morami
  • 313
  • 1
  • 5
  • Thanks, but I don't know the name of python files in `sources` that's why this should work dynamically. – Gocht Jun 20 '17 at 21:29
  • To use classes in `source_one` by calling only `sources` -> `sources.Class_in_source_one` I need to add `from source_one import Class_in_source_one` in `__init__.py`. But, once again, I do not know the name of files in `sources` – Gocht Jun 20 '17 at 21:36
1

It's kind of trick ;) but works:

import os
fileslist = os.listdir("sources")
for item in fileslist:
    if item.endswith("py") and item != "__init__.py":
        exec ("from sources.%s import *" %(item.split('.')[0]))
RaminNietzsche
  • 2,683
  • 1
  • 20
  • 34