Skip to content

Instantly share code, notes, and snippets.

@JungeAlexander
Created November 27, 2014 17:22
Show Gist options
  • Star 60 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save JungeAlexander/6ce0a5213f3af56d7369 to your computer and use it in GitHub Desktop.
Save JungeAlexander/6ce0a5213f3af56d7369 to your computer and use it in GitHub Desktop.
Import modules from parent folder in Python
# From http://stackoverflow.com/a/11158224
# Solution A - If the script importing the module is in a package
from .. import mymodule
# Solution B - If the script importing the module is not in a package
import os,sys,inspect
current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parent_dir = os.path.dirname(current_dir)
sys.path.insert(0, parent_dir)
import mymodule
@coolcat-310
Copy link

Thank you

@sciconaut
Copy link

Thanks! But it would also work to just do sys.path.insert(0, '..') and to omit the two lines before, right?

@Huong-nt
Copy link

thank you!

@this-oliver
Copy link

mucho gracias

@yasindagasan
Copy link

cheers

@gitumarkk
Copy link

Thanks :)

@zehanort
Copy link

zehanort commented Aug 15, 2019

Relative import does not seem to work since Python3.something:
ValueError: attempted relative import beyond top-level package
edit: both current and parent directories are packages (i.e. they include a __init__.py file). What is going on?

@RashminDungrani
Copy link

Thanks man :)

@ldesousa
Copy link

ldesousa commented Jan 23, 2020

I can confirm this formulation fails in Python 3.6: ValueError: attempted relative import beyond top-level package.

@atakanokan
Copy link

Thanks! But it would also work to just do sys.path.insert(0, '..') and to omit the two lines before, right?

Did this work?

@fx-kirin
Copy link

I made this.

@ZenTheDev
Copy link

this returns a value error: ValueError: attempted relative import beyond top-level package
it's honestly stupid that it is this hard to import from parent directories in python.

@asiguqaCPT
Copy link

Thanks mate.

@Fischbrot
Copy link

Thanks m8

@chaine29ma
Copy link

Thanks

@AlekefromKz
Copy link

Thanks!

@Mercurise
Copy link

thanks!!!

@gabsdocompiuter
Copy link

i've recently had problems with this, here are my solution:

project
|__foo
   |__ bar.py
|__test
   |__ my_test.py

my_test.py:

import sys
sys.path[0] += '\\..'

from foo.bar import MyClass

@VisheshKumar821
Copy link

Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment