Skip to content

tests: use __file__ for package import#801

Merged
kennethreitz merged 1 commit into
realpython:masterfrom
tv3141:package_import_from_tests
Mar 10, 2017
Merged

tests: use __file__ for package import#801
kennethreitz merged 1 commit into
realpython:masterfrom
tv3141:package_import_from_tests

Conversation

@tv3141

@tv3141 tv3141 commented Feb 28, 2017

Copy link
Copy Markdown
Contributor

To import the package in tests/context.py one should use:

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

rather than:

sys.path.insert(0, os.path.abspath('..'))

This was already changed in kennethreitz/samplemod, but not in the guide itself.

Explanation:

According to the docs os.path.abspath(path) is equivalent to: normpath(join(os.getcwd(), path)).

os.getcwd() returns the path from where the Python interpreter was called, not the location of the executed file:

> tree dir1
dir1
└── dir2
    └── dir3
        └── rel_path.py
> cat dir1/rel_path.py
import os.path
print(os.path.abspath('..'))
print(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
> cd dir1/dir2/dir3
> python rel_path.py 
/home/user/dir1/dir2
/home/user/dir1/dir2
> cd ..
> python dir3/rel_path.py 
/home/user/dir1
/home/user/dir1/dir2

@kennethreitz kennethreitz merged commit 453cefb into realpython:master Mar 10, 2017
@kennethreitz

Copy link
Copy Markdown
Contributor

thanks!

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants