Bitten by my C/Java experience

Ian Kelly ian.g.kelly at gmail.com
Mon May 4 13:43:33 EDT 2015


On Mon, May 4, 2015 at 9:20 AM, Cecil Westerhof <Cecil at decebal.nl> wrote:
> Potential dangerous bug introduced by programming in Python as if it
> was C/Java. :-(
> I used:
>     ++tries
> that has to be:
>     tries += 1
>
> Are there other things I have to be careful on? That does not work as
> in C/Java, but is correct syntax.

Some other gotchas that aren't necessarily related to C/Java but can
be surprising nonetheless:

*    () is a zero-element tuple, and (a, b) is a two-element tuple,
but (a) is not a one-element tuple. Tuples are created by commas, not
parentheses, so use (a,) instead.

*    Default function arguments are created at definition time, not at
call time. So if you do something like:

    def foo(a, b=[]):
        b.append(a)
        print(b)

The b list will be the same list on each call and will retain all
changes from previous calls.

*    super() doesn't do what you might expect in multiple inheritance
situations, particularly if you're coming from Java where you never
have to deal with multiple inheritance. It binds to the next class in
the method resolution order, *not* necessarily the immediate
superclass. This also means that the particular class bound to can
vary depending on the specific class of the object.

*    [[None] * 8] * 8 doesn't create a 2-dimensional array of None. It
creates one list containing None 8 times, and then it creates a second
list containing the first list 8 times, *not* a list of 8 distinct
lists.

*    If some_tuple is a tuple containing a list, then some_tuple[0] +=
['foo'] will concatenate the list *but* will also raise a TypeError
when it tries to reassign the list back to the tuple.



More information about the Python-list mailing list