Use of [] as default in __init__ parameters

Bug #1183698 reported by Ladislav Smola
6
This bug affects 1 person
Affects Status Importance Assigned to Milestone
OpenStack Dashboard (Horizon)
Fix Released
Wishlist
Ladislav Smola

Bug Description

The [] shouldn't be used as default in __init__ parameters

e.g here
https://github.com/openstack/horizon/blob/master/horizon/tables/actions.py#L182
https://github.com/openstack/horizon/blob/master/horizon/tables/actions.py#L273

here is little example why not
http://pastebin.com/nRyRjhWu

the [] in the parameters creates object when the code is interpreted(when the instance of class is created). So then there is one object of array(list) for all objects that are created from that class

If my understanding of python is right, this applies not only for [] but for everything like tuples, strings.. (cause everything is object in python)

It is fine as long as you assign to the object attribute (because it creates new object). But any operation on the existing object, changes the one shared object (like append in the example).

This could lead to some pretty hard to find bugs.

The right way is to assign None and assign the [] in the __init__ body if the value is None

Revision history for this message
Ladislav Smola (lsmola) wrote :

this could be solved by https://bugs.launchpad.net/horizon/+bug/1182931

because there will be no default parameters of __init__ then

Every object attribute is set in the __init__ body

(it would be fixed for Horizon Actions at least)

Revision history for this message
Julie Pichon (jpichon) wrote :

Well spotted. Although, to clarify something in the bug description: this only applies to mutables like lists and arrays. Those should not be in the method definition. Strings, tuples are immutable and fine to use in this context. Thanks for the bug report!

http://effbot.org/zone/default-values.htm

Changed in horizon:
status: New → Confirmed
Revision history for this message
OpenStack Infra (hudson-openstack) wrote : Fix proposed to horizon (master)

Fix proposed to branch: master
Review: https://review.openstack.org/30755

Changed in horizon:
assignee: nobody → Ladislav Smola (lsmola)
status: Confirmed → In Progress
David Lyle (david-lyle)
Changed in horizon:
importance: Undecided → Wishlist
Revision history for this message
Ladislav Smola (lsmola) wrote :

hmm some weird connection of gerrit and launchpad, this code was merged some time ago

Changed in horizon:
status: In Progress → Fix Committed
Thierry Carrez (ttx)
Changed in horizon:
milestone: none → icehouse-2
status: Fix Committed → Fix Released
Thierry Carrez (ttx)
Changed in horizon:
milestone: icehouse-2 → 2014.1
To post a comment you must log in.
This report contains Public information  
Everyone can see this information.

Other bug subscribers

Remote bug watches

Bug watches keep track of this bug in other bug trackers.