Warning of missing side effects

Pascal Chambon chambon.pascal at wanadoo.fr
Sat May 2 05:56:28 EDT 2009


Tobias Weber a écrit :
> Hi,
> being new to Python I find remarkable that I don't see any side effects. 
> That's especially true for binding. First, it is a statement, so this 
> won't work:
>
>    if x = q.pop():
>       print x # output only true values
>
> Second, methods in the standard library either return a value OR modify 
> the reciever, so even if assignment was an expression the above wouldn't 
> work.
>
> Only it still wouldn't, because IF is a statement as well. So no ternary:
>
>    x = if True: 5 else: 7;
>
> However there is one bit of magic, functions implicitly return None. So 
> while the following will both run without error, only one actually works:
>
>    x = 'foo'.upper()
>    y = ['f', 'b'].reverse()
>
> Now I mentioned that the mutable types don't have functions that mutate 
> and return something, so I only have to remember that...
>
> But I'm used to exploiting side effect, and sometimes forget this rule 
> in my own classes. IS THERE A WAY to have the following produce a 
> runtime error?
>
>    def f():
>       x = 5
>       # no return
>
>    y = f()
>
> Maybe use strict ;)
>
>   
Hello

Just to note that if "['f', 'b'].reverse()" doesn't return the new 
value, there is a corersponding function : "reversed(mylist)" which does 
it (idem, sorted(list) <-> list.sort())  B-)

Concerning your question on warnings, well I guess that after a little 
time in python, you won't make mistakes on "side effects" anymore ;

But if you want to add checks to your methods, you should see towards 
decorators or metaclasses : they allow you to wrap your methods inside 
other methods, of which the only point couldbe, for example, to check 
what your methods returtn and raise a warning if it returns "None". But 
the problem is, sometimes you WANT them to return None....

If you want to detect methods that don't have explicit "return" 
statements, then you'll have to play with abstract syntax trees it 
seems... much trouble for not much gain.
I guess you'll quickly get the pythonic habits without needing all that ^^

Regards,
pascal




More information about the Python-list mailing list