سؤال

As my limited brain has come to understand it after much reading, relative imports bad, absolute imports good. My question is, how can one effectively manage a "live" and "development" version of a package? That is, if I use absolute imports, my live code and development code are going to be looking at the same thing.

Example

/admin/project1/__init__.py
               /scripts/__init__.py
                       /main1.py
                       /main2.py
               /modules/__init__.py
                       /helper1.py

with "/admin" on my PYTHONPATH, the contents of project1 all use absolute imports. For example:

main1.py

import project1.modules.helper1

But I want to copy the contents of project1 to another location, and use that copy for development and testing. Because everything is absolute, and because "/admin" is on PYTHONPATH, my copied version is still going to be referencing the live code. I could add my new location to PYTHONPATH, and change the names of all files by hand (i.e. add "dev" to the end of everything), do my changes/work, then when I'm ready to go live, once again, by hand, remove "dev" from everything. This, will work, but is a huge hassle and prone to error.

Surely there must be some better way of handling "live" and "development" versions of a Python project.

هل كانت مفيدة؟

المحلول

You want to use virtualenv (or something like it).

$ virtualenv mydev
$ source mydev/bin/activate

This creates a local Python installation in the mydev directory and modifies several key environment variables to use mydev instead of the default Python directories. Now, your PYTHONPATH looks in mydev first for any imports, and anything you install (using pip, setup.py, etc) will go in mydev. When you are finished using the mydev virtual environment, run

$ deactivate

to restore your PYTHONPATH to its previous value. mydev remains, so you can always reactivate it later.

نصائح أخرى

@chepner's virtualenv suggestion is a good one. Another option, assuming your project is not installed on the machine as a python egg, is to just add your development path to the front of PYTHONPATH. Python will find your development project1 before the regular one and everyone is happy. Eggs can spoil the fun because they tend to get resolved before the PYTHONPATH paths.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top