Skip to content

Commit

Permalink
code
Browse files Browse the repository at this point in the history
  • Loading branch information
voldemortX committed Dec 26, 2021
1 parent cdcc256 commit 5e92c21
Show file tree
Hide file tree
Showing 5 changed files with 78 additions and 1 deletion.
31 changes: 30 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,31 @@
# magic-import
# magicimport

Voldemort's Python import helper

```
pip install magicimport
```

## Import from uninstalled Python directories

Say you have a directory (relative path `../../dir_a`) like this:

```
├── ../../dir_a
├── utils
│ ├── util_a.py
│ └── ...
└── ...
```

You want `func_a` from `utils.util_a.py`:

```
from magicimport import import_from
with import_from('../../'):
from utils.util_a import func_a
func_a() # use func_a
```

The advantage of **magicimport** is: outside of the `with` statement, your `sys.path` remains unchanged.
1 change: 1 addition & 0 deletions magicimport/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .import_from import import_from
19 changes: 19 additions & 0 deletions magicimport/import_from.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Import with sys.path.insert
import os
import sys
from contextlib import contextmanager


@contextmanager
def import_from(path):
# A package importer that leaves no trace.
# Say you want this function: package_path.xxx.yyy.zzz
# with import_from(package_path):
# from xxx.yyy import zzz
# zzz()
try:
abs_path = os.path.abspath(path)
sys.path.insert(0, abs_path)
yield
finally:
sys.path.pop(0)
6 changes: 6 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[build-system]
requires = [
"setuptools>=42",
"wheel"
]
build-backend = "setuptools.build_meta"
22 changes: 22 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import setuptools

with open("README.md", "r", encoding='utf-8') as fh:
long_description = fh.read()

setuptools.setup(
name="magicimport",
version="0.1.0",
author="Zhengyang Feng",
author_email="[email protected]",
description="Voldemort's Python import helper.",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/voldemortX/magic-import",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.5',
)

0 comments on commit 5e92c21

Please sign in to comment.