How to move Python script from one subpackage to another directory / package while maintaining backward compatibility

I have a common Python code base, and I am responsible for the code that others depend on. I need to move modules from one subpackage to another directory / package to reorganize it. How to do this in the safest way?

If I just translate the code, I have to worry about others who use it, who may not have redirected their import. If it moves and code users do not change their import, their code will unexpectedly fail if the import fails.

How can I ensure a smooth transition? Can I just copy the code and leave the old code until the import is changed? Are there any reservations to be aware of? What if I use import *in combination with __all__? In which case will I have to maintain imports from the old location indefinitely?

+4
source share
2 answers

Recently, I was asked to move the code from one subpackage to another at work, and the approach I used did not seem immediately obvious to other developers, so I am documenting it here for others.

. script, . .

, , .

:

  • . CVS, . (, mercurial, subversion git) mv , . git:

    git mv /location/old/script.py /location/new/script.py
    

:

unittests, __init__.py, . , __init__.py ,

  1. , , ,

    /location/old/script.py:

    from location.new.script import *
    

    , , , . __init__.py, , __init__.py.

. import * __all__. __all__, . :

from location.new.script import *
# names not in the new.script __all__:
from location.new.script import foo, bar, baz 

__init__.py sys.modules :

from location.new import script
import sys
sys.modules['location.old.script'] = script

sys.modules , . , os.path Python. sys.modules. , , , Python.

, . , , .

: script ( , !), .

:

, , :

(import|from).*location\.old.*script

Unix ( Cygwin), :

grep -rEe "(import|from).*location\.old.*script" .

IDE .

, , , . :

import location.old.script

import location.new.script

from location.old import script

from location.new import script 

.

:

. - , , .

: script

. - /, , . , , , .

, , , .

, , , . , .

+7

chuckmove . chuckmove - , , .

chuckmove --old sound.utils --new media.sound.utils src

... src , sound.utils media.sound.utils. Python. from x import y, import x.y.z as w ..

0

All Articles