yes with your code it accepts somthing like const int too ,which I don't want to. OK cool.The code has two __import__ statements: m = __import__('dir1.'+subdir1, fromlist=[file1]) .. m = __import__(file2, fromlist=[class_inside_file2]) The first one makes sense - it is roughly the equivalent of doing from dir1.subdir1 import file1 but allows for the subdirectory and file to be provided dynamically. It is the second statement that I don't understand why it works. It looks like it should be the equivalent of from file2 import class_inside_file2 This shouldn't work as file2.py is in subdir1, but my current working directory is two levels above that. Additionally, all of the __init__.py files are empty. As you would expect, the second import statement fails with an ImportError if it is run by itself. However, after the first import statement has run the second one works. Why? ./dir1/__init__.py ./dir1/subdir1/__init__.py ./dir1/subdir1/file1.py ./dir1/subdir1/file2.py ./dir1/subdir2/__init__.py ./dir1/subdir2/file1.py ./dir1/subdir2/file2.py However the 2nd __import__ command you've posted fails as expected: $ python Python 2.7.6 (default, Nov 18 2013, 11:23:24) [GCC 4.2.1 Compatible Apple LLVM 4.2 (clang-425.0.24)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> subdir1 = 'subdir1' >>> file1 = 'file1' >>> m = __import__('dir1.'+subdir1, fromlist=[file1]) 1.1 >>> file2 = 'file2' >>> class_inside_file2 = '*' >>> m = __import__(file2, fromlist=[class_inside_file2]) Traceback (most recent call last): File "", line 1, in ImportError: No module named file2 |
No comments:
Post a Comment