Python 3 – there shall be just int

Trying to contribute to the Flask plugin flask-login I just added these lines:

if isinstance(duration, (int, long)):
    duration = timedelta(seconds=duration)

Looking quite plausible, isn’t it? But lo and behold: it doesn’t work under Python 3.x. Dang!

The reason: Python 2 has two integer types: int and long. In Python 3 there is only int, which makes it necessary to distinguish between these two major versions. I’ve found a nice page which deals with this issue. Here is what You must do to make it work in both Python 2 and 3:

import sys
if sys.version_info < (3,):
    integer_types = (int, long,)
else:
    integer_types = (int,)

isinstance(1, integer_types)

 

Division in Python 2 vs 3

One major change in Python 3 is the implementation of the division operator /.

In Python 2 the division yielded a floor rounded integer when dividing two integers but a float when using a float as divider or divisor. Due to Python’s weakly typed nature this behavior could lead to some issues. So PEP-238 changed the behavior of the operator in Python 3 and introduced a new operator // in Python 2.2. Let’s have a look at the different behavior

 Python 2Python 3
1 / 200.5
1.0 / 20.50.5
3 / 211.5
3 // 211
3.0 // 21.01.0

If You want to use the new behavior of operator / from Python 3 in Python 2 you can do:

from __future__ import division

So have fun when You divide and conquer 🙂

Bringing AJAX to Flask – Part 1

Flask is a micro web framework which is really fun to use. With the following snippet You have a complete web app working within seconds.

from flask import Flask # 1
 
app = Flask(__name__)   # 2

@app.route('/')         # 3
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()           #4

All this snippet does is

  1. Importing the Flask module,
  2. Creating the app,
  3. Defining an so called endpoint and finally
  4. Running the web app in a container.

Flask brings its own WSGI server called “werkzeug”. Please use it just for development purposes. It is not suitable for live applications. Continue reading “Bringing AJAX to Flask – Part 1”