[Tutor] pointers for python?

Alan Gauld alan.gauld at blueyonder.co.uk
Sat Oct 4 19:00:16 EDT 2003


>> Why not the perfectly Pythonic solution
>>
>> >>> def inc(x):
>> ... return x + 1
>> ...
>
>I waned to do it without having to return a variable.... If it can't
be done.
>that's fine, but i was hoping to be able to do it without a
"return"....

Can you say why? The return method is by far the best technique,
its safe and makes the function reusable - it doesn't rely on a
variable called x existing somewhere. Its "the right way" to do it.

Using globals is possible but extremely bad practice and should be
avoided.




P. Brown in another reply gave you another answer involving the global
keyword -- but it's ugly and unpythonic IMHO and it only works for
global names (e.g. module-level). Right now I can't remember of any
other solution -- and I suspect any such would involve some dangerous
hackery.

Maybe the question should be: why do you want to write C code in
Python? In Python, variables are just names referencing an object
(said to be binded (bounded?) to that object). The line above

a = inc(a)

just rebinds the name "a" to whatever inc(a) returns. In C, a variable
is more of a placeholder -- a real location in memory -- that's why
you need, or at least one of the reasons why you need, all those
tricks with pass-by-reference and whatnot. So I repeat my question:

Why do you want to write C code in Python?

YMMV, but wouldn't it be better just trying to get in the Pythonic
mindset?

With my best regards,
G. Rodrigues






More information about the Tutor mailing list