A summary of points to keep in mind when creating a program that runs in the Python 2.5 environment. Mainly about functions that cannot be used in Python 2.5 (module build-in function) and countermeasures (alternative functions).
Modules and alternatives that are not available in Python 2.5.
The string module itself can be used in 2.5, but the string.Formatter class cannot be used.
7.1. string — Common string operations — Python 2.7.11 documentation
7.1.2. String Formatting
New in version 2.6.
message = "<format>".format(<parames>)
You cannot call the format function like this.
Use the old formatting method.
py:e.g.
message = "hogehoge %d %s" % (123, "test")
New in version 2.7.
The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.
15.5. optparse — Parser for command line options — Python 2.7.11 documentation
New in version 2.3.
optparse is a more convenient, flexible, and powerful library for parsing command-line options than the old getopt module. optparse uses a more declarative style of command-line parsing: you create an instance of OptionParser, populate it with options, and parse the command line. optparse allows users to specify options in the conventional GNU/POSIX syntax, and additionally generates usage and help messages for you.
optparse is included in Python 2.5 by default. Difficult to use compared to argparse. The difference between argparse and optparse is detailed below.
argparse vs. optparse — argparse v1.1 documentation
Install argparse as it is a separate package. https://pypi.python.org/pypi/argparse
Compatibility
argparse should work on Python >= 2.3, it was tested on:
- 2.3, 2.4, 2.5, 2.6 and 2.7
- 3.1, 3.2, 3.3, 3.4
The argparse package itself also supports Python 2.5.
16.6. multiprocessing — Process-based “threading” interface — Python 2.7.11 documentation
New in version 2.6.
multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. Due to this, the multiprocessing module allows the programmer to fully leverage multiple processors on a given machine. It runs on both Unix and Windows.
16.2. threading — Higher-level threading interface — Python 2.7.11 documentation
This module constructs higher-level threading interfaces on top of the lower level thread module. See also the mutex and Queue modules.
If it is an IO intensive program, it is effective to make it multithreaded even in threading. On the other hand, for CPU-intensive programs, threading is not a substitute for multiprocessing. With multiprocessing, the CPU load is distributed to multiple cores when multithreaded. However, with threading, the load is concentrated on one core, so even if it is multithreaded, the effect is small.
There is a module backported for Python 2.5.
https://pypi.python.org/pypi/multiprocessing/
Backport of the multiprocessing package to Python 2.4 and 2.5
18.2. json — JSON encoder and decoder — Python 2.7.11 documentation
New in version 2.6.
https://pypi.python.org/pypi/simplejson/
simplejson is a simple, fast, complete, correct and extensible JSON http://json.org encoder and decoder for Python 2.5+ and Python 3.3+. It is pure Python code with no dependencies, but includes an optional C extension for a serious speed boost.
The interface of simplejson is the same as the json module.
Although itertools itself can be used in Python 2.5, some functions have been added since 2.6.
9.7. itertools — Functions creating iterators for efficient looping — Python 2.7.11 documentation
New in version 2.3.
itertools.permutations(iterable[, r]) Return successive r length permutations of elements in the iterable. New in version 2.6.
itertools.product(*iterables[, repeat]) Cartesian product of input iterables. New in version 2.6.
None. Is this the only way to give up?
collections.Mapping
cannot be used. Even if you look at the official page, it seems that you can use it at 2.5 ...
8.3. collections — High-performance container datatypes — Python 2.7.11 documentation
New in version 2.4.
Running ʻis instance ({}, collections.Mapping)` in Python 2.5 fails. It succeeds in Python 2.7.
Python2.5
# python
Python 2.5.2 (r252:60911, Jan 24 2010, 14:53:14)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import collections
>>> isinstance({}, collections.Mapping)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'Mapping'
>>>
Python2.7
# python
Python 2.7.3 (default, Jan 2 2013, 16:53:07)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import collections
>>> isinstance({}, collections.Mapping)
True
>>>
Only when using isinstance, it can be handled by setting ʻisinstance ({}, dict)` or not using isinstance. If you want to create a class that inherits collections.Mapping, give up.
The following are measures related to is instance. There is a post from someone who faced this issue.
google app engine - Python 2.5 version of this method - Stack Overflow
I have the below function running fine on python 2.6, but appengine's production environment is 2.5 and it blows up on: AttributeError: 'module' object has no attribute 'Mapping' Does anyone have a solution for 2.5?
In the answer, use ʻis instance (val, dict)`. And stop using is instance. There is an answer.
- Try to stop using isinstance! – David Heffernan Feb 20 '11 at 15:59
- Or get rid of isinstance calls completely, since they are the enemy of duck typing. – Xiong Chiamiov Feb 20 '11 at 17:53
What does the comment that is instance is an enemy of dock typing mean?
Matsumoto Direct Programming Okite-Matsumoto Direct Programming Okite 4th (3): ITpro
Duck Typing doesn't care what class an object belongs to, it just cares about how it behaves (what methods it has). Duck Typing was coined by Dave Thomas, known as the "master programmer."
How to actually do Duck Typing
So what are the guidelines for practicing Duck Typing in a dynamic language? There is only one basic principle, at least this is all you need to remember.
● Avoid explicit type checking
Is instance is against this, isn't it?
What kind of code should I write for? When I searched for a concrete example, I found it.
Error importing 'Mapping' with Python 2.5 · Issue #8 · django-nonrel/django-dbindexer
Judgment is made by try --except instead of isinstance.
six Use 1.8.0 instead of the latest version. For details, refer to Notes on using six with Python 2.5 --Qiita.
Voluptuous See Installing Voluptuous with Python 2.5-Qiita.
Code like ↓ will result in an error when executed normally in Python 2.5.
with_sample.py(NG example)
with open("hoge", "w") as fp:
fp.write("foo")
NG example output
# python --version
Python 2.5.2
# python with_sample.py
with_sample.py:1: Warning: 'with' will become a reserved keyword in Python 2.6
File "with_sample.py", line 1
with open("hoge", "w") as fp:
^
SyntaxError: invalid syntax
Write from __future__ import with_statement
at the beginning of the program.
with_sample.py
from __future__ import with_statement
with open("hoge", "w") as fp:
fp.write("foo\n")
# python with_sample.py
# cat hoge
foo
success.
from __future__ import <feature>
is for using the functions standardized in the previous version in the past version. Below is the list.
28.11. future — Future statement definitions — Python 2.7.11 documentation
feature | optional in | mandatory in | effect |
---|---|---|---|
nested_scopes | 2.1.0b1 | 2.2 | PEP 227: Statically Nested Scopes |
generators | 2.2.0a1 | 2.3 | PEP 255: Simple Generators |
division | 2.2.0a2 | 3.0 | PEP 238: Changing the Division Operator |
absolute_import | 2.5.0a1 | 3.0 | PEP 328: Imports: Multi-Line and Absolute/Relative |
with_statement | 2.5.0a1 | 2.6 | PEP 343: The “with” Statement |
print_function | 2.6.0a2 | 3.0 | PEP 3105: Make print a function |
unicode_literals | 2.6.0a2 | 3.0 | PEP 3112: Bytes literals in Python 3000 |
Using as in except fails.
except_sample.py(NG example)
try:
raise ValueError("hoge")
except ValueError as e:
print e
NG example output
# python --version
Python 2.5.2
# python except_sample.py
except_sample.py:3: Warning: 'as' will become a reserved keyword in Python 2.6
File "except_sample.py", line 3
except ValueError as e:
^
SyntaxError: invalid syntax
The same program works with Python 2.6 and above.
python2.7
# python --version
Python 2.7.3
# python except_sample.py
hoge
Replace ʻas with
, `.
except_sample.py
try:
raise ValueError("hoge")
except ValueError, e:
print e
# python --version
Python 2.5.2
# python except_sample.py
hoge
By the way, ʻimportand
with` keywords can be used in Python 2.5 as well.
as_sample.py
from __future__ import with_statement
import simplejson as json
try:
raise ValueError("hoge")
except ValueError, e:
print e
with open("hoge", "r") as fp:
print fp.read()
# python --version
Python 2.5.2
# python as_sample.py
hoge
foo
However, if you do this, it will not work in Python 3 series. To maintain compatibility with Python 3:
How to write exception handling for compatibility between Python 2.5 and Python 3 --vmmhypervisor
Recommended Posts