I thought I understood how import worked...

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Aug 7 13:54:19 EDT 2012


On Tue, 07 Aug 2012 08:25:43 -0700, Roy Smith wrote:

> On Tuesday, August 7, 2012 9:52:59 AM UTC-4, Steven D'Aprano wrote:
> 
>> In general, you should avoid non-idempotent code. You should doubly
>> avoid it during imports, and triply avoid it on days ending with Y.

You seem to have accidentally deleted my smiley.

> I don't understand your aversion to non-idempotent code as a general
> rule.  Most code is non-idempotent.

That doesn't necessarily make it a good thing. Most code is also buggy.


> Surely you're not saying we should never write:
> 
>>>> foo += 1
> 
> or
> 
>>>> my_list.pop()
> 
> ???

Of course not. I'm not going so far as to say that we should always, 
without exception, write purely functional code. I like my list.append as 
much as anyone :)

But at the level of larger code units, functions and modules, it is a 
useful property to have where possible. A function is free to increment 
an integer, or pop items from a list, as much as it likes -- so long as 
they are *local* to the function, and get reset to their initial state 
each time the function is called with the same arguments.

I realise that many problems are most easily satisfied by non-idempotent 
tactics. "Customer orders widget" is not naturally idempotent, since if 
the customer does it twice, they get two widgets, not one. But such 
behaviour should be limited to the parts of your code which must be non-
idempotent.

In short, non-idempotent code is hard to get right, hard to test, and 
hard to debug, so we should use as little of it as possible.



-- 
Steven



More information about the Python-list mailing list