What is the argument for Python, which seems to frown upon importing from different directories?

This may be a broader question and more related to understanding the nature of Python and probably good programming practice in general.

I have a file called util.py. Over the past few months, he has been collecting many small functions that are useful in performing various machine learning tasks.

My thinking is this: I would like to continue adding important functions to this script when I go. Thus, I want to use import util.pyoften, now and in the future, in many unrelated projects.

But Python seems to feel that I only need to have access to the code in this file if it lives in my current state, even if the functions in this file are useful for scripts in different directories. I feel some reason for what works, which I do not fully understand; it seems to me that I will often be forced to make unnecessary copies.

If I have to create a new copy util.pyevery time I work from a new directory, in another project, it will not be long until I have many different versions / iterations of this file scattered throughout my hard drive in different states. I do not want such a degree of modularity in my programming - for the sake of simplicity, repeatability and clarity, I want only one file to be in one place accessible to many projects.

Question in a nutshell: What is the argument for Python that seems to frown when importing from different directories?

+4
source share
3 answers

If your file util.pycontains functions that you use in many different projects, then this is actually a library, and you should pack it as such so that you can install it in any Python environment with one line ( python setup.py install) and update it if it is necessary (Python packaging has several functions for tracking and updating library versions).

, , , , , util.py PYTHONPATH ( "" ). , , ImportError, : ? ?

, , -, , .

, , , , , ( ) , .

// , "util", . ? "" : , , , .

+3

: /you/want/to/import/from . __init__.py , utils.py , python . __init__.py , .

:

////proj1/
        __ init__.py
        utils.py
  ///school_projects/final_assignment/
        my_scrpyt.py

my_script.py

import sys
sys.path.append('/home/marcos/python/')
from proj1 import utils

MAX_HEIGHT = utils.SOME_CONSTANT
a_value = utils.some_function()
+1

First define an environment variable. For example, if you use bash, then put the following in the appropriate startup file:

export PYTHONPATH=/path/to/my/python/utilities

Now put your util.py and any of your other common modules or packages in this directory. Now you can import utilfrom anywhere, and python will find it.

0
source

All Articles