Carpetfizz Carpetfizz - 3 years ago 226
Python Question

Unable to import python file from different directory

I have the following folder hierarchy.


I simply want to import into my Jupyter Notebook. I tried doing it this way..

import sys
import os.path

sys.path.append(os.path.dirname(os.path.realpath('__file__')) + "/apriltag/python")

import apriltag

However, when I try to access a class from
, like so:


I get the following error:

AttributeError Traceback (most recent call last)
<ipython-input-74-d1254ec9a372> in <module>()
12 import apriltag
---> 14 print(apriltag.Detector)

AttributeError: module 'apriltag' has no attribute 'Detector'

Suggesting that the module was not imported correctly. I've tried creating
at the root of the
directory as well but the same thing occurred.

Answer Source

Ok, I'm going to buzz in a little bit early. I may have the solution to your problem. If I don't, we can go back to figuring it out.

As you've probably seen, the docs say

The directory containing the script being run is placed at the beginning of the search path,

Now, you're running my_notebook.ipynb, so it's directory is the very beginning of the search path. And you probably have an __init.py__ file in the apriltag directory that's at the same level. As such, it's being found as a module, and loaded. And there are no .py files in that "module", and nothing in your __init.py__ there, so it's loading as an empty module.

Instead, don't try modifying the sys.path directory. Do make empty __init.py__ files in both the apriltag and the python directories.

Then, you should be able to do the following:

from apriltag.python import apriltag

The apriltag that gets imported should be the one you need. (And dir(apriltag) will give you much nicer results.)

Generally, I always set up all my code in directories with empty and invoke them all with the from syntax. It made modules a lot easier to handle.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download