Monday, May 20, 2013

Why I Don't Like Python Anymore

Introduction
It was few years back in my first year of studies when my friend told me about Python. Then, it was great for me. One-liners could read ftp folders, web pages, interact with operation system, list comprehension, injecting code into life programs, nested functions, procedural as object oriented programming styles, etc. All of this in builtin libraries with simple but yet quite functional editor, supported with great documentation. I wrote my first studies project in Python and I was proud with it a little . During the following years, I was using Python for writing simple scripts to automate my professional work as PHP programmer. Python was and I still think is a better language than PHP. After that, I started to work as .NET/C# developer. It has a different syntax but C similarities let me learn it quite quickly. Framework .NET is a powerful tool also so I didn't touch Python for 2 or 3 years at least for anything longer than a few lines.

But a week or so ago, I decided to write a simple script to automate reading whole RSS channel. I wanted it to filter it for only the news that I was interested in. I decided to use Python for it. I was also considering PowerShell since it is built into Windows and it has a benefit from .NET. But I don't like its weird syntax, and since I wanted to just write this script and not struggle with syntax errors, I chose Python. I don't want to say that I made an mistake. It is still a powerful language and I manage to write this script quickly, but... there was some misunderstanding. Maybe I am more experienced. Or spoiled with C#, or used to it. Or just picky. Nonetheless, I decided to share this with the world.

One of the things was global versus local scope clash. I probably would get over it if not other things.

Let us consider a little program like this:

global_var= 1

def func_with_local_scope():
    print(global_var)

func_with_local_scope()
print(global_var)

I does a really simple thing: prints value '1' two times. Despite the fact that func has its own local scope aside from global scope, it will work because the interpreter will think about 'global_var' variable as global. It is correct behavior. Now let us change a bit:

global_var= 1

def inc():
    print(global_var)
    global_var+=1

inc()
print(global_var)

And... it will fail. Why?

  File "test.py", line 4, in inc
    print(global_var)
UnboundLocalError: local variable 'global_var' referenced before assignment

My first reaction was: "Huh?" How it is not assigned? It is done right before this function. Let's inspect scopes inside 'inc' function:

GLOBALS:

Read more: Codeproject
QR: Inline image 1