Install a local/personal library so it can be imported directly by a python project

Viewed 402

I have a silly question, but I haven't found any mention of it so far. I created a .py file in Python containing all of my functions that I am using for a job. Whenever I need to use them in a script, I have to address the path to the folder where the .py file is located, like the script below.

import os
os.chdir('...\\path-to-my-file')
import my-file as mfl

My question is: is there any way I can save the .py file with my functions right at the root of Anaconda and call it the same way I call Numpy, for example? I know that the libraries are in the 'C:\Users\User\anaconda3\Lib' folder, so I could save directly to that folder and call it in a more simplified way, like:

import numpy as np
import my-file as mfl

If this is feasible, would there be a standardized way to write the code?

2 Answers

In order to be able to import mypackage the same way you do with any other module, the correct approach is to use pip locally:

python -m pip install -e /path_to_package/mypackage/

  • python -m ensures you are using the pip package from the same python installation you are currently using.

  • -e makes it editable, i/e import mypackage will reload after you make some changes, instead of using the cached one.

mypackage must be an installable package, i/e contain an __init__.py file, and a basic setup.py (or pyproject.toml file for pipenv)

minimal setup.py

from setuptools import find_packages, setup

setup(
    name='mypackage',          # Required
    version='0.0.1',           # Required
    packages=find_packages(),  # Required
)

the package structure must be like this:

mypackage/
    setup.py
    mypackage/    <----- this is a folder inside the other `mypackage/` folder
        __init__.py

or as a tree:

└── python_perso                folder
    └── mypackage                   folder
        ├── mypackage                   folder
        │   └── __init__.py
        └── setup.py

[edit] after installation, the directory will look like this:
(for a package named mypackage)

└── python_perso
    └── mypackage
        ├── mypackage
        │   ├── __init__.py
        │   └── __pycache__
        │       └── __init__.cpython-38.pyc
        ├── mypackage.egg-info
        │   ├── PKG-INFO
        │   ├── SOURCES.txt
        │   ├── dependency_links.txt
        │   └── top_level.txt
        └── setup.py

5 directories, 7 files

I would suggest you create an Environment Variable called PYTHONPATH which will point you to additional functions. It is better to leave your anaconda root as it is if you are unsure of what you are doing. More on this here.

Related