Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I learn Python 2 if I already know Python 3?

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?

like image 239
Orcris Avatar asked Jan 22 '12 22:01

Orcris


2 Answers

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:

  1. 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
    
  2. 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.

like image 125
senderle Avatar answered Sep 29 '22 20:09

senderle


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.

like image 27
Greg Hewgill Avatar answered Sep 29 '22 19:09

Greg Hewgill