Encapsulation, inheritance and polymorphism

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Jul 18 09:05:15 EDT 2012


On Wed, 18 Jul 2012 01:46:31 +0100, Andrew Cooper wrote:

> Take for example a Linux system call handler.  The general form looks a
> little like (substituting C for python style pseudocode)
> 
> if not (you are permitted to do this):
>     return -EPERM
> if not (you've given me some valid data):
>     return -EFAULT
> if not (you've given me some sensible data):
>     return -EINVAL
> return actually_try_to_do_something_with(data)
> 
> How would you program this sort of logic with a single return statement?

That's not terribly hard.

if not (you are permitted to do this):
    result = -EPERM
elif not (you've given me some valid data):
    result = -EFAULT
elif not (you've given me some sensible data):
    result = -EINVAL
else:
    result = actually_try_to_do_something_with(data)
return result


A better example would involve loops. I used to hate programming in some 
versions of Pascal without a break statement: I needed a guard variable 
to decide whether or not to do anything in the loop!

# pseudo-code
for i in 1 to 100:
    if not condition:
        do_something_useful()


Even with a break, why bother continuing through the body of the function 
when you already have the result? When your calculation is done, it's 
done, just return for goodness sake. You wouldn't write a search that 
keeps going after you've found the value that you want, out of some 
misplaced sense that you have to look at every value. Why write code with 
unnecessary guard values and temporary variables out of a misplaced sense 
that functions must only have one exit?



-- 
Steven



More information about the Python-list mailing list