[Tutor] Quick Pythonic Style Tips

Mats Wichmann mats at wichmann.us
Sat Jul 22 10:57:36 EDT 2017


On 07/22/2017 07:46 AM, Alan Gauld via Tutor wrote:
> On 22/07/17 12:20, Abdur-Rahmaan Janhangeer wrote:
> 
>> As a user switching between some languages, it took sometimes before i
>> discovered that there was a styling guide in python
> 
> There are style idioms in most languages although not always
> written down as clearly as in PEP8. That having been said
> they should be viewed as guides not rules. In addition there
> are often local style guides that must be followed in
> a particular company.
> 
>> i'd like to know if there was a specific C++ or java> style of doing things which should be avoided ?

I'd like to contibute a rather different sort of tidbit to what Alan
wrote: be really careful about using mutable data types in function
calls, as class variables, and just in general.  Here's a quick example
of a classic "trap":

# append value to list, if list omitted return a new list
def func(val, alist=[]):
    alist.append(val)
    print alist
    return alist

func(1)
func(2)
func(3)

pop quiz :)  what is the output?

C++ has default arguments as well, so the output might be surprising in
that context:

[1]
[1, 2]
[1, 2, 3]

Instead of you getting a new empty list each time 'func' is called
without a second argument, the default list is part of the function.
Python runs the function code when it comes across it, creating a
function object which is then used each time the function is called, so
this initially empty list is reused each time.

To move the instantiation of the list to run-time, you could recode like
this:

def func(val, alist=None):
    if not alist:
        alist = []
    alist.append(val)
    print alist
    return alist

func(1)
func(2)
func(3)


This is really a bit of "Python style" (using None as the default to act
as a flag to do something special) that may not be reflected in the code
format parts of style guides.




More information about the Tutor mailing list