Reputation: 2031
I am the main guilty of a reasonably large Python package which is used internally in our organisation. I am in the process of preparing the package for Python3; for the code I have control over myself this is quite doable - but there are many scripts "out in the wild" which will break if/when the organisation default interpreter is yanked up to 3.x. The typical situation is as follows:
Some random script I do not have conrol over:
#!/usr/bin/env python # By manipulating the environment I will ...
# ... eventually switch this to pick up python3
import company.package # This is Python3 safe.
...
print "This - will fail hard"
What I would like to do (if possible) was to insert some global warning directives in the "company.package" code which I control - so that users can get a warning before the global interpreter is yanked up to Python3. Is this possible?
Upvotes: 1
Views: 325
Reputation: 33046
You can detect when a script is run in Python 2.x and issue an update warning like this:
import warnings
import sys
if sys.version_info < (3,0):
warnings.warn("company.package will be ported to Python 3 soon. Make sure that your script is Py3k-safe!")
Unfortunately, there is no way to ensure that a Python script will run smoothly in Python3, apart from human inspection based on static analysis (e.g. with 2to3
tool) and/or extensive unit testing.
EDIT: Porting to Python 3 is not only a matter of syntax, but involves module renaming (like urllib
, which was split, or cStringIO
) and conceptual changes (like the bytearray/string distinction). There is no import
magic to check that.
Upvotes: 3