[Tutor] Quick Pythonic Style Tips
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=):
pop quiz :) what is the output?
C++ has default arguments as well, so the output might be surprising in
[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
def func(val, alist=None):
if not alist:
alist = 
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