I have some knowledge of Python 3 (I'm not a beginner, but I'm not an expert). I'm interested in web development, so I want to use Django. What are the differences between the two versions of Python? How should I switch from 3 to 2.x?
They aren't so different. Almost everything you learned in Python 3 will transfer to Python 2. I would suggest that you simply dive in. Occasionally you'll see an error message, but most of the time they'll be self-explanatory.
My bet is that learning Django will be way harder than getting used to Python 2.
You might find the six
library helpful if you want to write code that is robustly backwards-compatible. Otherwise, I can only think of two things that might be important to know in advance as you go backwards to Python 2:
Avoid using old-style classes. In Python 3, you can declare a class like this, without any problem:
class Foo:
pass
In Python 2, if you do that, you get an old-style class, which you probably don't want. But you won't get any error messages about this, so subtle inheritance bugs might arise and stay hidden for a long time before causing problems. So in Python 2, remember to explicitly inherit from object
:
class Foo(object):
pass
Avoid using range(n)
, at least for large values of n
. In Python 3, range
returns an intelligent iterator, but in Python 2, range
returns an actual list. For large ranges, it can burn up a lot of memory. To get the behavior of Python 3's range
in Python 2, use xrange(n)
. Similar caveats apply to dictionary keys()
, values()
, and items()
methods. They all return lists in Python 2. Use the iterkeys()
, itervalues()
, and iteritems()
methods to save memory.
There are several other excellent answers to this question that cover a few other details, such as unicode
support.
If you already are familiar with Python 3, then there are almost no differences you will have to worry about when coding in Python 2. The most user-visible differences have to do with details of the print
statement, which you probably won't be using for Django anyway.
So, just write code, and ask about any specific problems you might encounter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With