0

How do I import from a higher level directory in python?

For example, I have:

/var/www/PROJECT/subproject/_common.py 
/var/www/PROJECT/subproject/stuff/routes.py

I want to import variable A in _common.py to routes.py

# routes.py

import os, sys   
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from _common import A

but I get the error:

ImportError:cannot import name 'A'
임지웅
  • 121
  • 1
  • 1
  • 8

2 Answers2

0

OLD VERSION

To solve the issue replace ".." with os.pardir:

import os, sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)))
from _common import A

NEW VERSION

The code above does not solve the problem in the question because the true problem lies in the project structure not in the particular line. The problem is circular import. The problem became clear after the full traceback has been provided. Here is the simple way to reproduce the issue - consider 3 files...

main.py:

import a

a.py:

import b
A = 'A'

b.py:

from a import A

... the error is:

ImportError: cannot import name 'A'

OR

b.py:

import a
BB = a.A

... the error is:

AttributeError: module 'a' has no attribute 'A'

The solution to the problem has been discussed many times - search on SO

  • same here, i tried, still import error saying cannot import name 'A' – 임지웅 Nov 21 '18 at 13:14
  • @임지웅 Does your `_common.py` script really contain `A`? Maybe `A` is located inside some function or conditional structure? Can you provide the code of `_common.py`? –  Nov 21 '18 at 13:33
  • from flask import Flask, render_template, url_for, redirect, request, Blueprint from flaskext.mysql import MySQL from __init__ import app from db_controller.function import get_db import os, sys A = get_db('mysql') – 임지웅 Nov 21 '18 at 13:38
  • @임지웅 I tested the code with `_common.py` containing a single line `A = "this is A"`. And the code works. Try this very simple version. Also, please edit your question - add `_common.py` content and full traceback for the error. –  Nov 21 '18 at 13:45
0

Change file directory:

import os, sys   
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),"../../project")))
from _common import A
Ali.Turkkan
  • 266
  • 2
  • 11
  • i tried, still import error saying cannot import name 'A' – 임지웅 Nov 21 '18 at 13:14
  • You have to go from routes.py to two top file paths. You enter PROJECT after the two files are up. And enter the subproject directory and you can import import _common.py. Path = "../../subproject". If still not working, make sure it has A function in _common. @임지웅 – Ali.Turkkan Nov 21 '18 at 13:34
  • As I understand it, A is not a function. A is a variable. You can't import a variable. Your create a functioan and return A variable. After import and use A variable. @임지웅 – Ali.Turkkan Nov 21 '18 at 13:45