Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

My Number 1 Java to Python Gotcha

DZone's Guide to

My Number 1 Java to Python Gotcha

· Java Zone
Free Resource

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

Fredrik Lundh is almost certainly a benevolent alien in disguise, sent to Earth to help the pitiful human race drag itself up out of the muck.

In a recent post, he touched on something that burned me BAD when I first started slinging pythion: using mutables as default parameters.

My particular run-in was a cousin of what Fredik describes, using a mutable as a default class attribute. I had a class like this:

class MyPage(object):
errors = []
def __init__(self):
# set me up

def run(self):
try:
self.build_page()
except:
self.errors.append("Oops. Something went wrong")
My problem was that I was setting a mutable as a default attribute value. This meant that each instance of MyPage was sharing the same error list; analagous to a static class variable in Java. It wasn't long before everything had errors, since the array just kept growing. This happened in a production environment. Sub-awesome indeed. What I SHOULD have done is this:

class MyPage(object):
errors = None
def __init__(self):
# set me up
self.errors = []

def run(self):
try:
self.build_page()
except:
self.errors.append("Oops. Something went wrong")

The __init__ clears out the array each time a new object is created. No sharing between instances. No pain.

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:

Published at DZone with permission of Aaron Oliver. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}