4

I followed advice here on stackoverflow on how to import a class from a path outside of the root folder: How to dynamically load a Python class Does python have an equivalent to Java Class.forName()?

Unfortunately this raises the error: ValueError: Empty module name

It is my understanding that import should not return an empty module, like the load_source method from imp. So I do not understand this error nor how to approach it.

What am I implementing wrong here? Could you tilt me into the right direction here?

Thanks!

Code:

klass = __import__('..folder.module.Class_A')
some_object = klass()

class class_B(some_object):
    def run(self):
        print ('Test OK!')

Imported class (content of module):

class Class_A():
    def __init__(self, arg1, *args):
def run(self):
    pass
1
  • "__import__('..folder.module.Class_A')" is not what is suggested in your link. I suggest you reread it. Commented Sep 20, 2014 at 1:38

1 Answer 1

4

First of all you are not using import correctly.

Option 1:

According to https://docs.python.org/2/library/functions.html#import you should be doing:

klass = __import__('folder.module', globals(), locals(), ['Class_A'], -1)

Now if you want Class_A itself you should do:

some_object = klass.Class_A

Then you can inherit from it using:

class class_B(some_object):
    def run(self):
        print ('Test OK!')

Option 2:

from folder.module import Class_A

Then you can inherit from it using:

class class_B(Class_A):
    def run(self):
        print ('Test OK!')

Note: In folder.module folder should be a python package and module should be a python module

Sign up to request clarification or add additional context in comments.

1 Comment

Downvoting and not making a comment is very not helpful!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.