

First Impressions of Python from a Java Developer - jbail
http://jeffbail.com/first-impressions-of-python-from-a-java-devel

======
stevelosh
The thing that really made my jaw drop the first time I saw it was list
comprehensions.

    
    
        allowed_usernames = [user.username for user in all_users if user.is_admin()]
    

This Stack Overflow answer makes it seem like Java developers should be at
least impressed with them as I was:
[http://stackoverflow.com/questions/899138/python-like-
list-c...](http://stackoverflow.com/questions/899138/python-like-list-
comprehension-in-java)

~~~
swannodette
This feature is of course lifted from Haskell - another jaw dropping language.

~~~
stevelosh
Yep. Python has a wonderful habit of taking the awesome features of other
languages and expanding on them.

List comprehensions were added in 2.0, generator comprehensions were added in
2.4, and dictionary comprehensions came in 2.7

~~~
nickbarnwell
Just found a reason to upgrade to 2.7...

------
d0m
My first impression is that this guy is 10 years late!

And I agree that it's funny for a Java programmer to be able to read a file
with open('bleh').read() instead of that 15 stream buffer stream reader stream
whatever line of code.

~~~
Luyt
...and if you're processing text files line by line, it isn't even necessary
to call read() or readlines() on the file, since a file object supports
iteration. You could say:

    
    
        for line in open("todo.txt"):
            # do something with line

~~~
rbanffy
You could also

    
    
        [ do_something_to(line) for line in open('todo.txt') ]

~~~
xiongchiamiov
Although you'd probably want to replace those square brackets with parens to
make it a generator, if you're dealing with a largish file.

~~~
rbanffy
Indeed. Hope it's not a huge file.

------
erikano
> _The one pitfall for block indenting in Python is reading online
> documentation. The block indenting gets screwed up sometimes._

Sometimes, pressing "view source" in the browser and looking at the HTML will
reveal what it was supposed to look like.

~~~
Semiapies
Mind, this is not unique to Python. It's a bit more irritating in Python
because indentation is significant, but I've seen a lot of unindented samples
of other languages with correspondingly reduced readability. For some reason,
I've most seen such sloppiness in presenting Javascript code.

~~~
wvenable
Yes, but the reduced readability is an easy fix in that case. You can copy the
code into an editor and indent based on the braces or have your editor auto-
format the code. Badly formatting code in other languages does not change the
meaning of the code as it does in Python.

~~~
Semiapies
I'm not sure what your point is, as I already acknowledged that in the comment
you're responding to, while making it clear that my concern was readability of
code examples on a web page. Are you going for a cheap "gotcha"?

~~~
wvenable
My point is poor readability of samples in other languages is a really simple
fix. I have cut'n'pasted many code samples into editors just to re-intent them
for reading. With Python, sadly, it's just not possible to that roboticly.

------
guelo
I never understood why Java never got some nice utility functions for dealing
with common stream actions such as looping through an InputStream or slurping
a text file. Every developer ends up carting around their own version of these
functions when they should just be in the standard library. Many complaints
about Java's verboseness have to do with this type of boilerplate that could
easily be hidden away in utility functions.

~~~
lusis
Isn't that what Apache Commons is for? It's sad that you have to resort to
that but at least someone stepped up to the plate.

------
kenjackson
_In Java, that would take a handful of code, a try/catch block, a loop, some
sort of buffer and would ultimately create much more verbose, much less
readable code._

How do you get away with none of this in Python? You need a try/catch block to
catch exceptions on open and read don't you? There's no guarantee the file
exists, or you have permission, or enough memory to read the file.

And while you don't necessarily need a for-loop to process the data, you often
will.

~~~
bad_user

          You need a try/catch block to catch exceptions on open and read don't 
          you? There's no guarantee the file exists, or you have permission, or 
          enough memory to read the file.
    

Doing a try / catch implies that you can recover from it.

That isn't the case most of the times (you cannot get extra permissions to a
file, you cannot recover from not having enough memory, and if the file is
missing that's a bug).

What usually happens in both Java and Python is that you have a top-level
try/catch that catches everything and just does logging.

The difference is that in Java you catch and re-throw the exception, or put
the exception type in the method's interface, which IMHO leaks encapsulation.
Or just turn everything into RuntimeExceptions with a little compiler-plugin
magic.

Either way, checked exceptions are a big fail.

~~~
kenjackson
Doing a try/catch doesn't imply anything, except that an exception occurred
that you caught. Behavior after that is completely app dependent.

Top-level try/catch blocks that simply do logging and nothing below that may
not always be a bad idea, but its usually a sign of a poorly designed app.

And why can't you get extra-permissions or recover from not having enough
memory? I've certainly worked on systems with the later, where we catch an
OutOfMemoryException and then do some stuff we're required to do -- including
in some situations to get memory back (which is for example, why we'll often
pre-JIT and keep loaded code required to free up memory).

Checked exceptions are a big fail, but largely because they're a broken way of
thinking about exceptions (and why Java was the last major language to have
them).

EDIT: I glossed over the fact that you may have been actually getting at which
is the requirement associated with checked exceptions. You're absolutely
correct there. No argument from me. I wasn't think of that originally, as I'm
not a Java dev.

~~~
rbanffy
> Doing a try/catch

Doing try/catch tells the compiler you know what you are doing. I prefer
compilers that take that as a given.

------
gaoshan
Given the limited set of things he goes over (with the exception of block
indenting trouble) you could replace "Python" with "PHP" and still have the
same article. Don't crucify me, just pointing that out.

~~~
xiongchiamiov
Or any semi-modern scripting language, for that matter.

~~~
gaoshan
Yep. I went to read it expecting some insight (as I don't know Java) but was
disappointed to see the article was so generic.

------
drats
I looked into groovy recently, and even as a python fanboy I can see how
awesome it is for someone who already knows java. It looks extremely close to
both python and ruby, and you can drop down to java anytime, use java
libraries anytime. It even has a pretty good rails clone called grails. Can
anyone from the java community explain to me why it hasn't taken off more?
Perhaps other JVM languages have stolen people away or split the people
looking for something else. I suppose with a 1.0 release in 2007 vs the early
and mid 90's for python and ruby respectively I should perhaps wait and see.

~~~
nickbarnwell
I just finished building an internal web application for my school entirely in
Java. From start to finish it took about eight hours, roughly the same amount
of time it would've taken in Python/Django or RoR, thanks to the Play
Framework.

Java doesn't need to be ridiculously verbose, others have mentioned much of
that verbosity stems from basic functions not being included in the standard
library. Python's opening of a file isn't any more elegant than Java's if you
look at the code behind open(), it's just abstracted away.

~~~
xiongchiamiov
There are some things that Java just _is_ more verbose at. For instance, my
pet peeve - accessor methods. Most other modern languages have properties,
which allow you to only write special cases when you need them.

~~~
nickbarnwell
This is one of the things that Play does well; setters and getters are
generated for you at runtime so you only have to write it as:

public Date submittedAt;

and set/get it as you would any other variable. Easily one of my favorite
things about the framework, and saves my { and } keys work as well.

------
jordanmessina
Wait till he discovers the awesomeness of first class objects and functions.

~~~
reinhardt
Or iterators/generators and itertools.

------
nivertech
One thing I dislike in Python's syntax is ":" at the end of some composite
statements, i.e. "if X:" or "else:". "else" is reserved word, why do I need to
append ":"?

Also how to do one-liners? ;)

~~~
xi
Just like semantic indentation, ":" is ABC's heritage. It was discovered that
newbie programmers comprehend block operations better when they end with ":".

[http://python-history.blogspot.com/2009/02/early-language-
de...](http://python-history.blogspot.com/2009/02/early-language-design-and-
development.html)

~~~
nivertech
back in time, there was several schools for language syntax design for
composite statements:

1\. "Open" statements (Pascal):

    
    
      IF x 
        THEN s1
        ELSE s2;
    
      IF x 
        THEN
          BEGIN
            s1;
            s2
          END
        ELSE
          BEGIN
            s3;
            s4
          END
    
      WHILE c DO s;
    
      WHILE c DO
      BEGIN
         s1;
         s2
      END
    

The problem with this design was need to use blocks (BEGIN ... END) and
complex rules in case of nesting.

2\. "Closed" statements (Algol 68)

    
    
      IF x 
        THEN 
           s1;
           s2
        ELSE 
           s3;
           s4
      FI // END IF
    
      WHILE c DO
         s1;
         s2
      OD // END WHILE
    

You can see new kind of parenthesis IF-FI, DO-OD, etc.

I more like "closed" syntax. But C syntax with it's brackets blocks "{...}"
instead of "BEGIN...END" made this less an issue.

------
RodgerTheGreat
What's the big deal about I/O in Java? I always thought things fit together
pretty easily. Just want to read some integers from a file?

    
    
      Scanner in = new Scanner(new File(filename));
      while(in.hasNextInt()) {
        ...
      }
    

How about reading ints over a network connection?

    
    
      Socket sock = new Socket("foo", 10101);
      Scanner in = new Scanner(sock.getInputStream());
      ...
    

If you find yourself reading an entire file into an array, you want to easily
access the lines of a file in an iterable fashion, or any of this other stuff,
just write a 5 line method once and forget about it. Problem solved. There are
features from other languages you _can't_ replicate that easily in Java, but
arguing about builtin methods is rather silly.

------
torme
Totally nitpicking here but != and == should typically only be used when
comparing primitive values.

For example, if you have an Integer object (not a primitive int) you should
use .equals() and not == for comparison. The == is used for comparing
references and not values.

That said, this only illustrates some extra complexity in Java.

~~~
Jabbles
Argh, the complexities of Java!

Integer a = new Integer(10);

Integer b = new Integer(10);

Integer c = new Integer(1000);

Integer d = new Integer(1000);

a==b is true

c==d is false

~~~
reinhardt
Sorry to break it out to you but you picked a bad example; the equivalent
Python code has the same WTF effect:

Python 2.6.6 (r266:84292, Oct 17 2010, 15:53:05)

[GCC 4.4.3] on linux2

>>> a = int(10)

>>> b = int(10)

>>> c = int(1000)

>>> d = int(1000)

>>> a is b

True

>>> c is d

False

~~~
Jabbles
Wow! Really? (I'm not a Pythonator.)

Same reasoning as Java?

~~~
reinhardt
Basically yes, although it is not part of the language definition and should
not be relied on. It's just an implementation artifact of CPython, and not
only that but the threshold of which integers are cached changes for different
Python versions.

------
justin_vanw
Blog posts like this are self-congratulatory wastes of time.

I would suggest an alternate title: "Opinions on something I don't know much
about yet."

------
f7u12
This is how I felt: <http://imgur.com/1FFB0.jpg>

------
badmash69
My heart bleeds for you . Its really does. Writing boilerplate code -- oh the
horror !

And yet an evil part of my brain would like to subject you to annotations and
spring config xml files. But that can wait till you Python lovers grow up and
get a real job !!

