Pascal int()
Michael Hudson
mwh21 at cam.ac.uk
Fri Mar 17 09:39:49 EST 2000
Michal Bozon <bozon at natur.cuni.cz> writes:
> Hi.
>
> I want to have a function (of course in Python) equivalent to Pascal
> function int(). (It increments an integer stored in argument by 1).
>
> This should do folowwing:
>
> >>> i = 10
> >>> int(i)
> >>> i
> 11
>
> eventually:
>
> >>> i = 10
> >>> int(i, 2)
> >>> i
> 12
>
> I have no idea how to do it.
Which is because you can't. Variables are just names in Python;
there's no way inside a function to find out how a value that was
passed into you got there.
ASCII art coming up:
Suppose `int' is defined starting
def int(v):
...
in the interpreter toplevel you have this situation:
|-------| /-----------------\
| "int" | ======> | function object |
|-------| \-----------------/
|-----| /----------------\
| "i" | ======> | the integer 10 |
|-----| \----------------/
then when you execute "int(i)" you enter the execution context of the
int function where the namespace looks like:
|-----| /----------------\
| "v" | ======> | the integer 10 |
|-----| \----------------/
There's no way to find out starting from here that the variable "i" a
stack frame up points to the value that was passed in.
You can do this, though:
>>> def incr(l): l[0]=l[0]+1
>>> i=[10]
>>> incr(i)
>>> i
[11]
because lists are mutable.
Soz,
M.
PS: Actually what I said above isn't strictly true if you're willing
to do insane things like pulling apart the call stack and decompiling
bytecode. You don't want to do this ...
--
very few people approach me in real life and insist on proving they are
drooling idiots. -- Erik Naggum, comp.lang.lisp
More information about the Python-list
mailing list