As a Java programmer learning Python, what should I look out for?

Question:

Much of my programming background is in Java, and I’m still doing most of my programming in Java. However, I’m starting to learn Python for some side projects at work, and I’d like to learn it as independent of my Java background as possible – i.e. I don’t want to just program Java in Python. What are some things I should look out for?

A quick example – when looking through the Python tutorial, I came across the fact that defaulted mutable parameters of a function (such as a list) are persisted (remembered from call to call). This was counter-intuitive to me as a Java programmer and hard to get my head around. (See here and here if you don’t understand the example.)

Someone also provided me with this list, which I found helpful, but short. Anyone have any other examples of how a Java programmer might tend to misuse Python…? Or things a Java programmer would falsely assume or have trouble understanding?

Edit: Ok, a brief overview of the reasons addressed by the article I linked to to prevent duplicates in the answers (as suggested by Bill the Lizard). (Please let me know if I make a mistake in phrasing, I’ve only just started with Python so I may not understand all the concepts fully. And a disclaimer – these are going to be very brief, so if you don’t understand what it’s getting at check out the link.)

  • A static method in Java does not translate to a Python classmethod
  • A switch statement in Java translates to a hash table in Python
  • Don’t use XML
  • Getters and setters are evil (hey, I’m just quoting 🙂 )
  • Code duplication is often a necessary evil in Java (e.g. method overloading), but not in Python

(And if you find this question at all interesting, check out the link anyway. 🙂 It’s quite good.)

Asked By: froadie

||

Answers:

The biggest one I can think of is not understanding or not fully utilizing duck typing. In Java you’re required to specify very explicit and detailed type information upfront. In Python typing is both dynamic and largely implicit. The philosophy is that you should be thinking about your program at a higher level than nominal types. For example, in Python, you don’t use inheritance to model substitutability. Substitutability comes by default as a result of duck typing. Inheritance is only a programmer convenience for reusing implementation.

Similarly, the Pythonic idiom is “beg forgiveness, don’t ask permission”. Explicit typing is considered evil. Don’t check whether a parameter is a certain type upfront. Just try to do whatever you need to do with the parameter. If it doesn’t conform to the proper interface, it will throw a very clear exception and you will be able to find the problem very quickly. If someone passes a parameter of a type that was nominally unexpected but has the same interface as what you expected, then you’ve gained flexibility for free.

Answered By: dsimcha
  • Don’t put everything into classes. Python’s built-in list and dictionaries will take you far.
  • Don’t worry about keeping one class per module. Divide modules by purpose, not by class.
  • Use inheritance for behavior, not interfaces. Don’t create an “Animal” class for “Dog” and “Cat” to inherit from, just so you can have a generic “make_sound” method.

Just do this:

class Dog(object):
    def make_sound(self):
        return "woof!"

class Cat(object):
    def make_sound(self):
        return "meow!"

class LolCat(object):
    def make_sound(self):
        return "i can has cheezburger?"
Answered By: Ryan Ginstrom

One thing you might be used to in Java that you won’t find in Python is strict privacy. This is not so much something to look out for as it is something not to look for (I am embarrassed by how long I searched for a Python equivalent to ‘private’ when I started out!). Instead, Python has much more transparency and easier introspection than Java. This falls under what is sometimes described as the “we’re all consenting adults here” philosophy. There are a few conventions and language mechanisms to help prevent accidental use of “unpublic” methods and so forth, but the whole mindset of information hiding is virtually absent in Python.

Answered By: John Y

The most important thing, from a Java POV, is that it’s perfectly ok to not make classes for everything. There are many situations where a procedural approach is simpler and shorter.

The next most important thing is that you will have to get over the notion that the type of an object controls what it may do; rather, the code controls what objects must be able to support at runtime (this is by virtue of duck-typing).

Oh, and use native lists and dicts (not customized descendants) as far as possible.

Answered By: Caleb Hattingh

The way exceptions are treated in Python is different from
how they are treated in Java. While in Java the advice
is to use exceptions only for exceptional conditions this is not
so with Python.

In Python things like Iterator makes use of exception mechanism to signal that there are no more items.But such a design is not considered as good practice in Java.

As Alex Martelli puts in his book Python in a Nutshell
the exception mechanism with other languages (and applicable to Java)
is LBYL (Look Before You Leap) :
is to check in advance, before attempting an operation, for all circumstances that might make the operation invalid.

Where as with Python the approach is EAFP (it’s easier to Ask for forgiveness than permission)

Answered By: sateesh

A corrollary to “Don’t use classes for everything”: callbacks.

The Java way for doing callbacks relies on passing objects that implement the callback interface (for example ActionListener with its actionPerformed() method). Nothing of this sort is necessary in Python, you can directly pass methods or even locally defined functions:

def handler():
   print("click!")
button.onclick(handler)

Or even lambdas:

button.onclick(lambda: print("click!n")) 
Answered By: Rafał Dowgird

The referenced article has some good advice that can easily be misquoted and misunderstood. And some bad advice.

Leave Java behind. Start fresh. “do not trust your [Java-based] instincts”. Saying things are “counter-intuitive” is a bad habit in any programming discipline. When learning a new language, start fresh, and drop your habits. Your intuition must be wrong.

Languages are different. Otherwise, they’d be the same language with different syntax, and there’d be simple translators. Because there are not simple translators, there’s no simple mapping. That means that intuition is unhelpful and dangerous.

  • “A static method in Java does not translate to a Python classmethod.” This kind of thing is really limited and unhelpful. Python has a staticmethod decorator. It also has a classmethod decorator, for which Java has no equivalent.

    This point, BTW, also included the much more helpful advice on not needlessly wrapping everything in a class. “The idiomatic translation of a Java static method is usually a module-level function”.

  • The Java switch statement in Java can be implemented several ways. First, and foremost, it’s usually an if elif elif elif construct. The article is unhelpful in this respect. If you’re absolutely sure this is too slow (and can prove it) you can use a Python dictionary as a slightly faster mapping from value to block of code. Blindly translating switch to dictionary (without thinking) is really bad advice.

  • Don’t use XML. Doesn’t make sense when taken out of context. In context it means don’t rely on XML to add flexibility. Java relies on describing stuff in XML; WSDL files, for example, repeat information that’s obvious from inspecting the code. Python relies on introspection instead of restating everything in XML.

    But Python has excellent XML processing libraries. Several.

  • Getters and setters are not required in Python they way they’re required in Java. First, you have better introspection in Python, so you don’t need getters and setters to help make dynamic bean objects. (For that, you use collections.namedtuple).

    However, you have the property decorator which will bundle getters (and setters) into an attribute-like construct. The point is that Python prefers naked attributes; when necessary, we can bundle getters and setters to appear as if there’s a simple attribute.

    Also, Python has descriptor classes if properties aren’t sophisticated enough.

  • Code duplication is often a necessary evil in Java (e.g. method overloading), but not in Python. Correct. Python uses optional arguments instead of method overloading.

    The bullet point went on to talk about closure; that isn’t as helpful as the simple advice to use default argument values wisely.

Answered By: S.Lott
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.