Differences between revisions 1 and 2
Revision 1 as of 2006-02-17 15:35:37
Size: 782
Editor: 193
Comment:
Revision 2 as of 2006-02-17 15:48:44
Size: 1517
Editor: 193
Comment:
Deletions are marked like this. Additions are marked like this.
Line 5: Line 5:

= True Division =

Since the beginning, Python has yielded an integer result when
two integers are divided, e.g. 3/2 => 1. While correct if we
assume that dividing integers means integers division (the
remainder is accessible through the modulo operator %) it's
not always obvious to beginners. This behaviour will change in
a future Python version, so that a/b with yield a float as a
result regardless of the types of the numbers a and b, and
a new floor division operator // will perform integer
division. See See http://www.python.org/peps/pep-0238.html

    '''Use true and floor division in new code'''

{{{
from __future__ import division # Enable the new behaviour

f = 3/2 # 1.5

i = 3//2 # 1
}}}
Line 15: Line 38:
'''Use new style classes in new code'''     '''Use new style classes in new code'''

Python is a mature language, but it hasn't stopped evolving, and there are some issues to consider when coding Python, if you want your code to work with the latest version of Python in five five years from now...

True Division

Since the beginning, Python has yielded an integer result when two integers are divided, e.g. 3/2 => 1. While correct if we assume that dividing integers means integers division (the remainder is accessible through the modulo operator %) it's not always obvious to beginners. This behaviour will change in a future Python version, so that a/b with yield a float as a result regardless of the types of the numbers a and b, and a new floor division operator // will perform integer division. See See http://www.python.org/peps/pep-0238.html

  • Use true and floor division in new code

from __future__ import division # Enable the new behaviour

f = 3/2 # 1.5

i = 3//2 # 1

New style classes

Currently, there are two kinds of classes in Python. The 'classic' or old style classes, and the new style classes. Old style classes will go away in some future version, and while most code will still work when the default swaps from old style to new style, there are some differences in semantics, and the new style classes have some extra features. See http://www.python.org/doc/newstyle.html

  • Use new style classes in new code

Don't write

class X:
    pass

Write

class X(object):
    pass

FutureProofPython (last edited 2019-10-19 22:14:19 by FrancesHocutt)

Unable to edit the page? See the FrontPage for instructions.