Python first impressions
A few days ago I got my first Python project. I’d like to share references I’ve found, and what I like or dislike about the language. I hope to give insight to would-be Python dabblers and ideas to current Pythoneers.
Good resources I’ve found
I have found some good resources online for Python and Jython, but I know I didn’t find them all so if you Python-istas could put some in the comments I’d be very grateful :)
- The somewhat famous Python is not Java article
- Python Documentation Index
- Python 2.6.1 Docs
- Python Language Notes by Chris Rathman
- The Jython Project
What I like so far
I like that a lot of common operations are very easy. Take for example:
# 3 Hellos in Python hellos = 'Hello ' * 3
as opposed to
// 3 Hellos in Java
String hellos = "";
for (int i = 0; i < 3; i++) {
hellos += "Hello ";
}
There are a bunch of other features that come to mind, like string formatting, list manipulation, and variable and default-valued arguments. Oh, and of course closures are very straightforward (many thanks to Arnar for a real closure example):
def outer(your_name):
title = random.choice(["Mr", "Mrs", "Miss"])
def greeter(greeting):
print greeting, title, your_name
return greeter
g = outer("Eric") # invoke it
# g now contains a reference to the inner
# function, but as it references variables
# from the local scope of outer, the invocation
# data has been stored in a closure
# Execution of outer is finished, but g can
# still reference its local variables through
# the closure:
g("Hi") # prints "Hi Miss Eric" :D
I could go on and on, but you really ought to read the documentation to see all of its features. Actually there’s not all that much to it!
Troubles I have with it
I wish I could find more documentation with simple code examples. I’m sure there are a bunch of blog posts out there but it’d be nice if there were more included with the documentation.
Passing arguments by reference doesn’t seem to be possible, which is fine, but different. I’m not totally used to the lack of curly braces, but I like the fact that you must have good formatting to have runnable Python. I was surprised to learn that Python is strongly typed which in some way I think is odd because it seems like it’d be simpler if it was weakly typed.
a = "17" b = 25 print a + b # Nope!
One last thing is classes. I’m not sure I have my head around how they really work in Python. I’m sure I’ll get the hang of it soon.
Conclusion
Overall I’m thoroughly impressed with the language. There almost seems to be a Zen-like aura around Python code that is written with the simplicity the language creators intended.
Obviously I still have a lot to learn, so please help me out if you have some advice in the comments!
Hey Eric,
In case you haven’t seen it, there are a bunch of great tutorials listed on http://wiki.python.org/moin/BeginnersGuide/Programmers
That is probably a good place to start. Another nice thing I think that helps make python simpler to learn is the interactive console which works kinda like the Firebug console, letting you run code snippets on the fly.
> I’m not totally used to the lack of curly braces, but I like the fact that you must have good formatting to have runnable Python.
INDENT and DEDENT are your curly braces. If you’re indenting properly, curly braces are superfluous.
> I was surprised to learn that Python is strongly typed which in some way I think is odd because it seems like it’d be simpler if it was weakly typed.
Simpler, and insane and disgustingly error-prone like Javascript. In fact, I love the fact there’s no automatic text to number conversion. If I designed a programming language, “3″ + 3 would do little short of raising KillItWithFireException, in addition to attempting to delete the source code and log your user out.
LOL. I know that removing curly braces cleans up the language.
I guess I say that weak-typing would be simpler because Python itself seems to be a very “lazy” language and what’s lazier than “3″ + 3 = “33″? I see your point there, of course.
>Python itself seems to be a very “lazy” language and what’s lazier than “3″ + 3 = “33″? I see your point there, of course.
Huh, I was figuring that “3″ + 3 = 6 with weak typing. Guess that’s yet another reason for strong typing.
Eh well in Javascript “3″ + 3 is “33″ anyway. At least we won’t have to worry about it with Python :)
Python is a lazy language designed by people who actually have to implement real systems. Weak typing sounds cool when you first start learning programming, but leads to insane amount of pain because of the rather ridiculous amount of non-trivial non-obvious semantics that have to go with it.
As said, is “3″+3 = 33 or 6?
The only sensible answer is that it’s equal to:
Traceback (most recent call last):
File “”, line 1, in
TypeError: cannot concatenate ’str’ and ‘int’ objects
Eric, you should check out the activestate site for code snippets.
http://code.activestate.com/recipes/langs/python/
Dive into python: http://diveintopython.org/ has been a great resource for me as a programmer trying to learn Pythong, coming from another language.
> Passing arguments by reference doesn’t seem to be possible…
In python you should think of a variable name as a sort of ‘tag’ which references an object in memory somewhere, and when you pass an argument to a function it is ALWAYS that reference (or name) which you are passing around.. so in fact python can ONLY pass by reference.
Actually, no.
Simple “primitives” (like variables that hold numbers) are always passed by value.
Anything more complex (lists, objects, etc) are passed by reference by default.
I forget about strings – but you can write a simple test function to figure it out.
Strings are immutable, just like integers so they are passed by value as well. sorry for not making the distinction, perhaps its better to say all mutable objects are passed by reference, while immutable ones (tuples, strings and integers) are passed ‘by value’. In reality it best to not think in terms of ‘by value’ or ‘by reference’ when using python, you’re simple passing names around.
OK I get it so it’s kinda like Java in that way. Atoms are passed by value and everything else by reference. Gotcha :)
Not quite.
This is something you really should understand, otherwise you will make mistakes and be confused. It’s easy, just a bit different from what you’re used to from other languages.
Python doesn’t have variables, it has names. Names are like tags on objects. When you pass a name, you’re passing a reference to the object. Whether you can modify the object in place or not depends on the type of object (ints & strings no; lists & dicts & sets yes).
Details here:
http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables
Also see the references at the end.
OK thanks David, you obviously have great examples there :). I’m learning a lot.
passing by reference is possible but awkward. you need to wrap your value in a mutable thingie, like a list, dict or class and change that:
def ref1(a):
a[0] = 1
l = [0]
ref1(a)
print l
or
def ref2(a):
a.param = 1
class Struct: pass
v = Struct()
v.param = 0
ref2(v)
print v.param
you get the idea.
Thanks baczek. I thought it should be possible but I just hadn’t gotten it ’til today.
Thanks for all your help, guys!
That closure example does not create a closure. The inner function is called inside the scope of the outer and only a value is returned.
To create a closure, return the inner function only and call it outside of the outer scope.
Oops. You’re exactly right I totally spaced that, didn’t I? I’ll fix it, thanks!
Still missing a proper closure example :) See my more detailed reply on reddit :)
Good work though!
OK I stole your example verbatim :D. Interestingly, I pulled my last example almost straight from Venkat Subramanium’s book: Programming Groovy…
Hey, I’m exactly in the same shoes! Strong Java background, started writing a service to run on Google App Engine this weekend. First impressions: kewl, but I don’t like it:
1) still don’t get the motivation behind weak typing in an enterprise-grade app
2) lots of helper functions you call passing objects to them – looks weird to me
3) really miss the curly braces; can set up Eclipse to format java code upon save so that formatting would be the same project-wide -> that ‘ident right or won’t run’ looks weird
4) all that __xxx__ == “__yyy__”, _xxx & __xxx stuff, arrr!
5) don’t declare that a function returns smth
6) PyDev doesn’t compare to java tooling, e.g. debugging is very basic
Things are likely to change as get used to Python, but still, Java feels like a far better designed language to be used on daily basis. Python is more like shell scripting on steroids.
Eric, what would you say?
Don’t take this as an attack :)
1) What do you mean by enterprise? If you mean lots of people of various skill levels will be programming – then yes, strong typing is a benefit. But weak typing, as well as other dynamic features, allow a tightly knit team to produce a lot of functionality quickly in a maintainable package.
2) What do you mean? Almost everything you pass is an object. Do you have specific examples in mind?
3) That’s just because you are used to curly braces. This is a minor syntactic issue – and I would bet if you stick with it for a while it will grow on you. Personally I find the lack of unnecessary (you do indent anyways, right?) braces contributes to readability – both by things being cleaner and people indenting properly.
4) All that what? if __name__ == “__main__” you mean? That’s the only case.. and the _x and __x are just namespacing devices orthogonal to the module system to indicate the role of a symbol. Again a minor thing that doesn’t matter for language quality.
5) Every function returns something – so why would you declare it? (Note, a function without a return statement returns None)
6) This is a very valid point. Python doesn’t have very good IDEs, but then again they are not needed as much as for Java.
Java is not a very well designed language (partly the reason why you almost *need* an IDE to use it). Backwards compatibility issues are keeping designers off from correcting their initial mistakes. I’m not saying Python doesn’t have it warts.. but I don’t agree we can declare a winner in terms of language design.
My advice: look deeper than syntax and library idiosyncrasies. Once you start making use of the dynamic features, you’ll miss them when you are working in Java.
I understand that it’s hard to find good IDE support for Python. I’m sure it will get better.
Python looks like it has an interesting take on OO stuff, but it sounds well thought out. I do really appreciate its terseness as opposed to the verbosity of Java.
All in all, it’s just different. I’m sure we’ll both be python hackers in no time ;)
I think we can look forward to some killer NetBeans support for python in the future – until then its textmate for me…
> 2) lots of helper functions you call passing objects to them – looks weird to me
I strongly agree for this point. I think it should use ruby design that put those built-in methods into object so everything is more OO. Though ruby still has some methods which is act like built-in methods but actually it is live inside Kernel module just that it is expose globally.
> 4) all that __xxx__ == “__yyy__”, _xxx & __xxx stuff, arrr!
It seems wierd at first, but in the end I found it really useful for me.
Alex,
1) Python is strongly typed, but typing is not linked to variables. for example, ‘1′ + 1.0 would give an error as you cannot add a string to a float.
2) Python isn’t *solely* and OO language. OO sits beside procedural and functional idioms.
3) yep, it might at first look weird to indent for block structure, but people get used to it.
What is more off-putting is when indentation doesn’t matcch the logical structure of your code and that is what Python guards against.
4) Yep.
5) Or neccessarily what you think it takes either. This allows duck-typing and runtime flexibility.
6) Java *needs* those tools, and often abuses you by those tools generating lots of long-winded boilerplate code that you need a good IDE to navigate …
Hang in there. The rewards can be great!
- Paddy.
I took the plunge to try and switch all my tasks to python a couple months and its been mostly a joy.
I think the areas that seem most inconsistent are some of the built in functions.
Given that everything is an object it seems very odd to do the following:
my_list = [1,3,1,5]
len( my_list)
instead of my_list.length()
or do oddball things like the much maligned:
‘ ‘.join(my_list)
instead of my_list.join(‘ ‘)
There are also an increasing number of deprecated modules in the standard library that can make doing the python “one right way” thing hard (ie Popen, getopt, etc)
But overall – I have to say I’m extremely happy with the productivity I’m finding in Python.
-P
I completely understand your frustration with not finding full code examples. The main way I learn new programming languages is by checking out other people’s code (but this is usually hard to read or not well commented).
So I wrote a book aimed at young adults and nonprogrammers to teach them programming in Python. The book is Invent Your Own Computer Games with Python and is available for free under a Creative Commons license at http://pythonbook.coffeeghost.net
Instead of focusing on syntax and what not, the book has the complete source code for several small games (and teaches programming concepts from these examples). This is similar to the old game listings in Byte magazine for BASIC.
It’s also useful for people who know programming and just want to see some clear, concise Python code.
When learning Python don’t forget to check out BPython (http://www.bpython-interpreter.org/) or IPython (http://ipython.scipy.org/). They really make trying out snippets a joy.