Python, the beauty and the beast

I’ve started developing in Python at work about 2-3 months ago. I like Python as it has a very intuitive syntax and it’s very readable (the forced indentation probably helps a lot). It is really easy to write code using Python and the result is much cleaner than in other languages.

That being said …

One thing that catches me out however is my C++ inherited reliance on the compiler to catch trivial errors. With Python, I have to be more careful before I run the code and also test the code properly (and I mean every function/branch, etc.) just to make sure that it doesn’t crash because some uncaught silliness.

One other beginner’s mistake is to confuse global with local variables, a mistake that the interpreter punishes you silently for. For example:

global1 = ”

def ChangeGlobal():
global1 = ‘Hello globals!”

ChangeGlobal()
print global1

If you think the snippet above will greet you with a “Hello globals!” you better read that Python book again. What happens here is that within the ChangeGlobal function, the interpreter silently defines a local variable named global1 and assigns it the value ‘Hello globals!’. At the end of function call, the local is thrown away as the stack unwinds. The global variable global1 is unaffected as it refers to something else entirely.

The fix is simple once you realize what’s going on. You can change the function to this:

def ChangeGlobal():
global global1
global1 = ‘Hello globals!”

The line “global global1” tells the interpreter to search for a global named global1 instead of instantiating a local named global1.

All simple stuff that won’t power rockets, the only problem is that everything happens silently and you can fall foul without knowing. Maybe a bit confusing, the interpreter allows reads from globals without having to introduce them with the ‘global’ keyword. Which creates a sense of false security.

There are tools like pyChecker that help you catch problems, but they won’t catch all of them. And then, there’s the required discipline of running the tool regularly. Sometimes if you use some combination of C++ and Python, it makes the whole task much more difficult.

Advertisements

Tags:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: