Summary of points to keep in mind when writing a program that runs on Python 2.5

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).

module

Modules and alternatives that are not available in Python 2.5.

string module

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.

Countermeasures

Use the old formatting method.

py:e.g.


message = "hogehoge %d %s" % (123, "test")

argparse module

15.4. argparse — Parser for command-line options, arguments and sub-commands — Python 2.7.11 documentation

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.

Countermeasures

Use optparse module

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 the argparse package

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.

multiprocessing module

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.

Countermeasures

Use threading module

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.

Install the multiprocessing package

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

json module

18.2. json — JSON encoder and decoder — Python 2.7.11 documentation

New in version 2.6.

Countermeasures

Install the simplejson package

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.

itertools 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.

Countermeasures

None. Is this the only way to give up?

collections module

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
>>>

Countermeasures

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?

What is dock typing

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?

Avoid using is instance

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

Use duck-typing instead of Mapping for recursive settings updating. · django-nonrel/django-dbindexer@d11bdc3

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.

Python built-in feature

with keyword

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

Countermeasures

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

as keyword

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

Countermeasures

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, ʻimportandwith` 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

Summary of points to keep in mind when writing a program that runs on Python 2.5
When writing a program in Python
Things to keep in mind when developing crawlers in Python
Things to keep in mind when copying Python lists
Things to keep in mind when processing strings in Python2
Things to keep in mind when processing strings in Python3
Things to keep in mind when using Python with AtCoder
Things to keep in mind when using cgi with python.
I made a program to collect images in tweets that I liked on twitter with Python
Easy! Implement a Twitter bot that runs on Heroku in Python
Things to keep in mind when deploying Keras on your Mac
[Python] A program that rotates the contents of the list to the left
Here's a summary of things that might be useful when dealing with complex numbers in Python
[Python] A program that calculates the number of socks to be paired
I made a program to check the size of a file in Python
A program that removes duplicate statements in Python
Summary of how to use MNIST in Python
[Beginner] What happens if I write a program that runs in php in Python?
Things to keep in mind when using Python for those who use MATLAB
Summary of points I was addicted to running Selenium on AWS Lambda (python)
Things to keep in mind when doing Batch Prediction on GCP ML Engine
[Python] A program that counts the number of valleys
Summary of tools needed to analyze data in Python
A memorandum when writing experimental code ~ Logging in python
Things to note when initializing a list in Python
What's in that variable (when running a Python script)
A shell program that becomes aho in multiples of 3
[Python] A program that compares the positions of kangaroos.
A story that got stuck when trying to upgrade the Python version on GCE
[Python] A program that finds the shortest number of steps in a game that crosses clouds
[Introduction to Python] Summary of functions and methods that frequently appear in Python [Problem format]
Things to keep in mind when building automation tools for the manufacturing floor in Python
A note that runs an external program in Python and parses the resulting line
A little trick to know when writing a Twilio application using Python on AWS Lambda
A Python program in "A book that gently teaches difficult programming"
A general-purpose program that formats Linux command strings in python
Processing of python3 that seems to be usable in paiza
A program that automatically resizes the iOS app icon to the required image size in Python
Use a macro that runs when saving python with vscode
I made a program in Python that changes the 1-minute data of FX to an arbitrary time frame (1 hour frame, etc.)
[Python] Programming to find the number of a in a character string that repeats a specified number of times.
I tried "a program that removes duplicate statements in Python"
How to develop in a virtual environment of Python [Memo]
[GCP] A memorandum when running a Python program on Cloud Functions
Convenient writing method when appending to list continuously in Python
Use Heroku in python to notify Slack when a specific word is muttered on Twitter
How to get a list of built-in exceptions in python
A program that failed when trying to create a linebot with reference to "Dialogue system made with python"
A memo of writing a basic function in Python using recursion
A set of script files that do wordcloud in Python3
When you want to hit a UNIX command on Python
When I got a list of study sessions in Python, I found something I wanted to make
[Python3] List of sites that I referred to when I started Python
I wrote a class that makes it easier to divide by specifying part of speech when using Mecab in python
[Python] A program to find the number of apples and oranges that can be harvested
[Python] I tried to make a simple program that works on the command line using argparse.
A story that didn't work when I tried to log in with the Python requests module
[Subprocess] When you want to execute another Python program in Python code
I tried to create a server environment that runs on Windows 10
How to determine the existence of a selenium element in Python
A brief summary of Graphviz in python (explained only for mac)