Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #97060 > unrolled thread

Idiosyncratic python

Started bySteven D'Aprano <steve+comp.lang.python@pearwood.info>
First post2015-09-24 16:02 +1000
Last post2015-09-25 10:08 +1000
Articles 20 on this page of 24 — 15 participants

Back to article view | Back to comp.lang.python


Contents

  Idiosyncratic python Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2015-09-24 16:02 +1000
    Re: Idiosyncratic python Paul Rubin <no.email@nospam.invalid> - 2015-09-23 23:16 -0700
      Re: Idiosyncratic python Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2015-09-24 16:35 +1000
        Re: Idiosyncratic python Ben Finney <ben+python@benfinney.id.au> - 2015-09-24 16:54 +1000
          Re: Idiosyncratic python Steven D'Aprano <steve@pearwood.info> - 2015-09-25 11:08 +1000
        Re: Idiosyncratic python Terry Reedy <tjreedy@udel.edu> - 2015-09-24 02:54 -0400
    Re: Idiosyncratic python wxjmfauth@gmail.com - 2015-09-24 00:06 -0700
      Re: Idiosyncratic python Laurent Pointal <laurent.pointal@free.fr> - 2015-09-24 19:50 +0200
        Re: Idiosyncratic python Mark Lawrence <breamoreboy@yahoo.co.uk> - 2015-09-24 21:05 +0100
    Re: Idiosyncratic python jmp <jeanmichel@sequans.com> - 2015-09-24 11:12 +0200
    Re: Idiosyncratic python Mark Lawrence <breamoreboy@yahoo.co.uk> - 2015-09-24 14:09 +0100
    Re: Idiosyncratic python jmp <jeanmichel@sequans.com> - 2015-09-24 16:07 +0200
    Re: Idiosyncratic python Ian Kelly <ian.g.kelly@gmail.com> - 2015-09-24 08:26 -0600
    Re: Idiosyncratic python Chris Angelico <rosuav@gmail.com> - 2015-09-25 02:57 +1000
    Re: Idiosyncratic python jmp <jeanmichel@sequans.com> - 2015-09-24 20:04 +0200
    Re: Idiosyncratic python Ian Kelly <ian.g.kelly@gmail.com> - 2015-09-24 12:19 -0600
    Re: Idiosyncratic python Ned Batchelder <ned@nedbatchelder.com> - 2015-09-24 13:46 -0700
      Re: Idiosyncratic python Laura Creighton <lac@openend.se> - 2015-09-24 23:08 +0200
      Re: Idiosyncratic python Chris Angelico <rosuav@gmail.com> - 2015-09-25 07:49 +1000
      Re: Idiosyncratic python Steven D'Aprano <steve@pearwood.info> - 2015-09-25 10:55 +1000
    Re: Idiosyncratic python sohcahtoa82@gmail.com - 2015-09-24 15:32 -0700
    Re: Idiosyncratic python Mark Lawrence <breamoreboy@yahoo.co.uk> - 2015-09-25 00:40 +0100
    Re: Idiosyncratic python Akira Li <4kir4.1i@gmail.com> - 2015-09-25 03:04 +0300
    Re: Idiosyncratic python Steven D'Aprano <steve@pearwood.info> - 2015-09-25 10:08 +1000

Page 1 of 2  [1] 2  Next page →


#97060 — Idiosyncratic python

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2015-09-24 16:02 +1000
SubjectIdiosyncratic python
Message-ID<560391ea$0$2885$c3e8da3$76491128@news.astraweb.com>
I was looking at an in-house code base today, and the author seems to have a 
rather idiosyncratic approach to Python. For example:


for k, v in mydict.items(): 
    del(k)
    ...


instead of the more obvious

for v in mydict.values(): 
    ...



What are your favorite not-wrong-just-weird Python moments?



-- 
Steve

[toc] | [next] | [standalone]


#97061

FromPaul Rubin <no.email@nospam.invalid>
Date2015-09-23 23:16 -0700
Message-ID<87twqkbavx.fsf@jester.gateway.sonic.net>
In reply to#97060
Steven D'Aprano <steve+comp.lang.python@pearwood.info> writes:
> for k, v in mydict.items(): 
>     del(k)

That looks wrong: it's deleting k from what?

> instead of the more obvious
> for v in mydict.values(): 
>     ...

Maybe you mean

   while mydict:
      k, v = mydict.popitem()
      ...

[toc] | [prev] | [next] | [standalone]


#97062

FromSteven D'Aprano <steve+comp.lang.python@pearwood.info>
Date2015-09-24 16:35 +1000
Message-ID<560399b0$0$1511$c3e8da3$5496439d@news.astraweb.com>
In reply to#97061
On Thursday 24 September 2015 16:16, Paul Rubin wrote:

> Steven D'Aprano <steve+comp.lang.python@pearwood.info> writes:
>> for k, v in mydict.items():
>>     del(k)
> 
> That looks wrong: it's deleting k from what?

The local namespace.

py> k = 23
py> print k
23
py> del k
py> print k
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'k' is not defined

 
>> instead of the more obvious
>> for v in mydict.values():
>>     ...
> 
> Maybe you mean
> 
>    while mydict:
>       k, v = mydict.popitem()
>       ...


Hah, no, you're the second person to make that mistake! One of the guys I 
work with suggested `mydict = {}` to empty the dict.

`del k` (aside: no need for parens, del is a statement, not a function) 
doesn't delete the key from the dictionary. It just deletes the name k. The 
obvious intent is to iterate over the *values* of the dictionary, but the 
coder didn't know about values, so he iterated over (key,value) pairs, then 
deleted the key local variable (not the key in the dict!) to keep the 
namespace clean.



-- 
Steve

[toc] | [prev] | [next] | [standalone]


#97063

FromBen Finney <ben+python@benfinney.id.au>
Date2015-09-24 16:54 +1000
Message-ID<mailman.117.1443077664.28679.python-list@python.org>
In reply to#97062
Steven D'Aprano <steve+comp.lang.python@pearwood.info> writes:

> On Thursday 24 September 2015 16:16, Paul Rubin wrote:
>
> > Steven D'Aprano <steve+comp.lang.python@pearwood.info> writes:
> >> for k, v in mydict.items():
> >>     del(k)
>
> […] The obvious intent is to iterate over the *values* of the
> dictionary, but the coder didn't know about values, so he iterated
> over (key,value) pairs, then deleted the key local variable (not the
> key in the dict!) to keep the namespace clean.

That's not obvious to me. It's plausible, now that you say it. I find it
also plausible, though, that the author is under the mistaken impression
that the key and value must both be deleted, and has found a way that
appears to do that.

Perhaps what we're illustrating here is exactly why such idiosyncratic
code *is* bad: it obscures the intent of the code for programmers who
know idiomatic Python.

And those readers are hopefully the ones the author should be trying to
communicate to, on the theory that we've all got the goal to become a
programmer who knows idiomatic Python.

-- 
 \        “The fact of your own existence is the most astonishing fact |
  `\    you'll ever have to confront. Don't dare ever see your life as |
_o__)    boring, monotonous, or joyless.” —Richard Dawkins, 2010-03-10 |
Ben Finney

[toc] | [prev] | [next] | [standalone]


#97109

FromSteven D'Aprano <steve@pearwood.info>
Date2015-09-25 11:08 +1000
Message-ID<56049e7b$0$1601$c3e8da3$5496439d@news.astraweb.com>
In reply to#97063
On Thu, 24 Sep 2015 04:54 pm, Ben Finney wrote:

> Steven D'Aprano <steve+comp.lang.python@pearwood.info> writes:
> 
>> On Thursday 24 September 2015 16:16, Paul Rubin wrote:
>>
>> > Steven D'Aprano <steve+comp.lang.python@pearwood.info> writes:
>> >> for k, v in mydict.items():
>> >>     del(k)
>>
>> […] The obvious intent is to iterate over the *values* of the
>> dictionary, but the coder didn't know about values, so he iterated
>> over (key,value) pairs, then deleted the key local variable (not the
>> key in the dict!) to keep the namespace clean.
> 
> That's not obvious to me. It's plausible, now that you say it. I find it
> also plausible, though, that the author is under the mistaken impression
> that the key and value must both be deleted, and has found a way that
> appears to do that.

In fairness, I have seen the rest of the loop, which I excised, and it uses
the value v. There's no hint that the author thinks the dict has been
cleared by the end of the loop.




-- 
Steven

[toc] | [prev] | [next] | [standalone]


#97064

FromTerry Reedy <tjreedy@udel.edu>
Date2015-09-24 02:54 -0400
Message-ID<mailman.118.1443077670.28679.python-list@python.org>
In reply to#97062
On 9/24/2015 2:35 AM, Steven D'Aprano wrote:
> On Thursday 24 September 2015 16:16, Paul Rubin wrote:
>
>> Steven D'Aprano <steve+comp.lang.python@pearwood.info> writes:
>>> for k, v in mydict.items():
>>>      del(k)
>>
>> That looks wrong: it's deleting k from what?
>
> The local namespace.
>
> py> k = 23
> py> print k
> 23
> py> del k
> py> print k
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> NameError: name 'k' is not defined
>
>
>>> instead of the more obvious
>>> for v in mydict.values():
>>>      ...
>>
>> Maybe you mean
>>
>>     while mydict:
>>        k, v = mydict.popitem()
>>        ...
>
>
> Hah, no, you're the second person to make that mistake! One of the guys I
> work with suggested `mydict = {}` to empty the dict.
>
> `del k` (aside: no need for parens, del is a statement, not a function)
> doesn't delete the key from the dictionary. It just deletes the name k. The
> obvious intent is to iterate over the *values* of the dictionary, but the
> coder didn't know about values, so he iterated over (key,value) pairs, then
> deleted the key local variable (not the key in the dict!) to keep the
> namespace clean.

but, but, each iteration rebinds k, so del k is only needed after the 
loop .. unless one is super fanatic about cleanliness within the loop ;-)


-- 
Terry Jan Reedy

[toc] | [prev] | [next] | [standalone]


#97065

Fromwxjmfauth@gmail.com
Date2015-09-24 00:06 -0700
Message-ID<3901ccc9-2ff9-49f2-bafb-fb4326a868b4@googlegroups.com>
In reply to#97060
Le jeudi 24 septembre 2015 08:02:38 UTC+2, Steven D'Aprano a écrit :
> 
> 
> What are your favorite not-wrong-just-weird Python moments?
> 
> 
Showing how to make Python 3.5.0 crash by
just using an "é", U+00E9.

jmf

[toc] | [prev] | [next] | [standalone]


#97082

FromLaurent Pointal <laurent.pointal@free.fr>
Date2015-09-24 19:50 +0200
Message-ID<560437e5$0$3354$426a74cc@news.free.fr>
In reply to#97065
wxjmfauth@gmail.com wrote:

> Le jeudi 24 septembre 2015 08:02:38 UTC+2, Steven D'Aprano a écrit :
>> 
>> 
>> What are your favorite not-wrong-just-weird Python moments?
>> 
>> 
> Showing how to make Python 3.5.0 crash by
> just using an "é", U+00E9.

Like this ?


Python 3.5.0 (default, Sep 24 2015, 19:47:57) 
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> s = "\u00E9"
>>> print(s)
é


[toc] | [prev] | [next] | [standalone]


#97088

FromMark Lawrence <breamoreboy@yahoo.co.uk>
Date2015-09-24 21:05 +0100
Message-ID<mailman.142.1443125146.28679.python-list@python.org>
In reply to#97082
On 24/09/2015 18:50, Laurent Pointal wrote:
> wxjmfauth@gmail.com wrote:
>
>> Le jeudi 24 septembre 2015 08:02:38 UTC+2, Steven D'Aprano a écrit :
>>>
>>>
>>> What are your favorite not-wrong-just-weird Python moments?
>>>
>>>
>> Showing how to make Python 3.5.0 crash by
>> just using an "é", U+00E9.

Would you like to show us all how, or do you think you'd be far too 
embarassed by once again showing that you haven't got the faintest idea 
what you're talking about?

>
> Like this ?
>
>
> Python 3.5.0 (default, Sep 24 2015, 19:47:57)
> [GCC 4.9.2] on linux
> Type "help", "copyright", "credits" or "license" for more information.
>>>> s = "\u00E9"
>>>> print(s)
> é
>

Your test must be wrong as the RUE knows everything.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

[toc] | [prev] | [next] | [standalone]


#97066

Fromjmp <jeanmichel@sequans.com>
Date2015-09-24 11:12 +0200
Message-ID<mailman.119.1443085975.28679.python-list@python.org>
In reply to#97060
On 09/24/2015 08:02 AM, Steven D'Aprano wrote:
> I was looking at an in-house code base today, and the author seems to have a
> rather idiosyncratic approach to Python. For example:
>
>
> for k, v in mydict.items():
>      del(k)
>      ...
>
>
> instead of the more obvious
>
> for v in mydict.values():
>      ...
>
>
>
> What are your favorite not-wrong-just-weird Python moments?

A lot of our in base weird python comes from heavily C-wired people:

The classic
for i in range(len(alist)):
   print alist[i]

with its twin brother

i=0
while i < len(alist):
   print alist[i]
   i += 1

And the even more annoying

result = Result()
getResult(result)

JM



[toc] | [prev] | [next] | [standalone]


#97070

FromMark Lawrence <breamoreboy@yahoo.co.uk>
Date2015-09-24 14:09 +0100
Message-ID<mailman.123.1443100205.28679.python-list@python.org>
In reply to#97060
On 24/09/2015 13:50, paul.hermeneutic@gmail.com wrote:
>  > A lot of our in base weird python comes from heavily C-wired people:
>  >
>  > The classic
>  > for i in range(len(alist)):
>  >   print alist[i]
>  >
>  > with its twin brother
>  >
>  > i=0
>  > while i < len(alist):
>  >   print alist[i]
>  >   i += 1
>  >
>  > And the even more annoying
>  >
>  > result = Result()
>  > getResult(result)
>  >
>  > JM
>
> Please follow up with good ways to write these. I hear that creating one
> really good way is a Python maxim.
>

for item in alist:
     print(item)

If you *think* you need the index:-

for i, item in enumerate(alist):
     print(i, item)
`i` defaults to 0, but there is a `start` keyword argument that lets you 
set it to anything you like.

Better IMHO is to see what the itertools module[1] offers, either 
directly or through recipes.  The latter are available on pypi as 
more-itertools[2].

[1] https://docs.python.org/3/library/itertools.html
[2] https://pypi.python.org/pypi/more-itertools/

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

[toc] | [prev] | [next] | [standalone]


#97075

Fromjmp <jeanmichel@sequans.com>
Date2015-09-24 16:07 +0200
Message-ID<mailman.127.1443103660.28679.python-list@python.org>
In reply to#97060
On 09/24/2015 02:50 PM, paul.hermeneutic@gmail.com wrote:
>  > A lot of our in base weird python comes from heavily C-wired people:
>  >
>  > The classic
>  > for i in range(len(alist)):
>  >   print alist[i]
>  >
>  > with its twin brother
>  >
>  > i=0
>  > while i < len(alist):
>  >   print alist[i]
>  >   i += 1
>  >
>  > And the even more annoying
>  >
>  > result = Result()
>  > getResult(result)
>  >
>  > JM
>
> Please follow up with good ways to write these. I hear that creating one
> really good way is a Python maxim.

for item in alist:
   print item

and

result = getResult()

For the later, the original weird form come from a C habit to allocate 
returned structures within the caller and provide a pointer to it so the 
function can fill the data in, otherwise the structure is lost as the 
stack is popped out and the structure content is garbage. None of this 
make any sense in python.

JM

[toc] | [prev] | [next] | [standalone]


#97077

FromIan Kelly <ian.g.kelly@gmail.com>
Date2015-09-24 08:26 -0600
Message-ID<mailman.130.1443104819.28679.python-list@python.org>
In reply to#97060
On Thu, Sep 24, 2015 at 8:07 AM, jmp <jeanmichel@sequans.com> wrote:
> result = getResult()
>
> For the later, the original weird form come from a C habit to allocate
> returned structures within the caller and provide a pointer to it so the
> function can fill the data in, otherwise the structure is lost as the stack
> is popped out and the structure content is garbage. None of this make any
> sense in python.

Only if the structure is allocated on the stack and returned by
pointer. If it's returned by value, then the content remains intact,
but at the expense of copying it. The other option of course would be
to allocate it on the heap and return the pointer, but this needlessly
incurs malloc overhead and creates an opportunity for a memory leak if
the variable is naturally stack-scoped. Python effectively takes this
option, as everything is allocated on the heap. Leaving it up to the
caller to provide a pointer also gives the caller the option of
allocating on the stack or the heap as best fits the context.

[toc] | [prev] | [next] | [standalone]


#97081

FromChris Angelico <rosuav@gmail.com>
Date2015-09-25 02:57 +1000
Message-ID<mailman.136.1443113877.28679.python-list@python.org>
In reply to#97060
On Fri, Sep 25, 2015 at 2:54 AM, Todd <toddrjen@gmail.com> wrote:
> Using list indexing with booleans in place of a ternary operator.
>
> a = False
> b = [var2, var1][a]
>
> Instead of:
>
> b = var1 if a else var2

Be careful - these are not semantically identical. The first one
evaluates both var1 and var2, while the second will evaluate only the
one it needs. This might be significant if they're not simple names.

ChrisA

[toc] | [prev] | [next] | [standalone]


#97083

Fromjmp <jeanmichel@sequans.com>
Date2015-09-24 20:04 +0200
Message-ID<mailman.137.1443117871.28679.python-list@python.org>
In reply to#97060
On 09/24/2015 04:26 PM, Ian Kelly wrote:
> On Thu, Sep 24, 2015 at 8:07 AM, jmp <jeanmichel@sequans.com> wrote:
>> result = getResult()
>>
>> For the later, the original weird form come from a C habit to allocate
>> returned structures within the caller and provide a pointer to it so the
>> function can fill the data in, otherwise the structure is lost as the stack
>> is popped out and the structure content is garbage. None of this make any
>> sense in python.
>
> Only if the structure is allocated on the stack and returned by
> pointer. If it's returned by value, then the content remains intact,
> but at the expense of copying it. The other option of course would be
> to allocate it on the heap and return the pointer, but this needlessly
> incurs malloc overhead and creates an opportunity for a memory leak if
> the variable is naturally stack-scoped. Python effectively takes this
> option, as everything is allocated on the heap. Leaving it up to the
> caller to provide a pointer also gives the caller the option of
> allocating on the stack or the heap as best fits the context.
>

I'm not an expert but I think this "return by value thing" is only for C++.
In vintage C, you can only return something that fits within a register.

Anyway, there's a lot of legit C code in which functions are plagued by 
'out parameters' and somehow it has transpired in some python code for 
no reason :o)

jm

[toc] | [prev] | [next] | [standalone]


#97084

FromIan Kelly <ian.g.kelly@gmail.com>
Date2015-09-24 12:19 -0600
Message-ID<mailman.138.1443118822.28679.python-list@python.org>
In reply to#97060
On Thu, Sep 24, 2015 at 12:04 PM, jmp <jeanmichel@sequans.com> wrote:
> I'm not an expert but I think this "return by value thing" is only for C++.
> In vintage C, you can only return something that fits within a register.

If that was true at one time, it was before ANSI C.

$ cat test.c
#include <assert.h>

struct foo {
  int a;
  long b;
  float c;
  double d;
};

struct foo get_foo() {
  struct foo value;
  value.a = 12;
  value.b = 92L;
  value.c = 4.5f;
  value.d = -21.5;
  return value;
}

int main() {
  struct foo value = get_foo();
  assert(value.a == 12);
  assert(value.b == 92L);
  assert(value.c == 4.5f);
  assert(value.d == -21.5);
  return 0;
}
$ gcc -Wall -O0 -std=c89 test.c
$ ./a.out
$

There is a danger however in that it's only a shallow copy. If any
struct members are pointers, then the pointer value will be copied,
not the thing pointed to.

[toc] | [prev] | [next] | [standalone]


#97091

FromNed Batchelder <ned@nedbatchelder.com>
Date2015-09-24 13:46 -0700
Message-ID<00884c56-4c94-406b-9902-b94dda9d66b3@googlegroups.com>
In reply to#97060
On Thursday, September 24, 2015 at 2:02:38 AM UTC-4, Steven D'Aprano wrote:
> What are your favorite not-wrong-just-weird Python moments?

I've seen this a number of times:

    dict_of_values.update({'key': some_value})

why not:

    dict_of_values['key'] = some_value

I've considered writing a Pylint plugin to flag these...

--Ned.

[toc] | [prev] | [next] | [standalone]


#97092

FromLaura Creighton <lac@openend.se>
Date2015-09-24 23:08 +0200
Message-ID<mailman.144.1443128954.28679.python-list@python.org>
In reply to#97091
In a message of Thu, 24 Sep 2015 13:46:27 -0700, Ned Batchelder writes:
>On Thursday, September 24, 2015 at 2:02:38 AM UTC-4, Steven D'Aprano wrote:
>> What are your favorite not-wrong-just-weird Python moments?
>
>I've seen this a number of times:
>
>    dict_of_values.update({'key': some_value})
>
>why not:
>
>    dict_of_values['key'] = some_value
>
>I've considered writing a Pylint plugin to flag these...
>
>--Ned.

A student today had a similar version of this one:

Every time he wanted to change the value of dictionary mapping he would
write:
w={'key': new_value}
dict_of_values.update(w)

Laura

[toc] | [prev] | [next] | [standalone]


#97096

FromChris Angelico <rosuav@gmail.com>
Date2015-09-25 07:49 +1000
Message-ID<mailman.148.1443131740.28679.python-list@python.org>
In reply to#97091
On Fri, Sep 25, 2015 at 7:08 AM, Laura Creighton <lac@openend.se> wrote:
> In a message of Thu, 24 Sep 2015 13:46:27 -0700, Ned Batchelder writes:
>>On Thursday, September 24, 2015 at 2:02:38 AM UTC-4, Steven D'Aprano wrote:
>>> What are your favorite not-wrong-just-weird Python moments?
>>
>>I've seen this a number of times:
>>
>>    dict_of_values.update({'key': some_value})
>>
>>why not:
>>
>>    dict_of_values['key'] = some_value
>>
>>I've considered writing a Pylint plugin to flag these...
>>
>>--Ned.
>
> A student today had a similar version of this one:
>
> Every time he wanted to change the value of dictionary mapping he would
> write:
> w={'key': new_value}
> dict_of_values.update(w)

That's a new one on me! The oddest dictionary code any of my students
has come out with (so far!) was a slavish habit of always iterating
over them thus:

for k,v in some_dict.items():

where some_dict is the only part that changed. So everywhere through
the code - even in nested loops - all dictionary iteration used "k"
and "v".

But I suspect it's exactly the same. Saw some code somewhere, found
that it worked, used it. If you don't understand something, don't
change it... which is a good policy in general, I suppose :)

ChrisA

[toc] | [prev] | [next] | [standalone]


#97108

FromSteven D'Aprano <steve@pearwood.info>
Date2015-09-25 10:55 +1000
Message-ID<56049b70$0$1618$c3e8da3$5496439d@news.astraweb.com>
In reply to#97091
On Fri, 25 Sep 2015 06:46 am, Ned Batchelder wrote:

> On Thursday, September 24, 2015 at 2:02:38 AM UTC-4, Steven D'Aprano
> wrote:
>> What are your favorite not-wrong-just-weird Python moments?
> 
> I've seen this a number of times:
> 
>     dict_of_values.update({'key': some_value})
> 
> why not:
> 
>     dict_of_values['key'] = some_value
> 
> I've considered writing a Pylint plugin to flag these...

Awesome! 

I haven't seen it in the wild, but there's this too:

    dict_of_values.update(key=some_value)



-- 
Steven

[toc] | [prev] | [next] | [standalone]


Page 1 of 2  [1] 2  Next page →

Back to top | Article view | comp.lang.python


csiph-web