Correction: Pascal inc(), not int()
Adrian Eyre
a.eyre at optichrome.com
Mon Mar 20 09:30:10 EST 2000
On Fri, 17 Mar 2000, Michal Bozon wrote:
> Hi.
>
> I want to have a function (of course in Python) equivalent to Pascal
> function inc(). (It increments an integer stored in argument by 1).
>
> This should do folowwing:
>
> >>> i = 10
> >>> inc(i)
> >>> i
> 11
>
> eventually:
>
> >>> i = 10
> >>> inc(i, 2)
> >>> i
> 12
Not possible without some extreme extension module hack, which is not
recommended. The problem is rebinding the new value into the calling
function's namespace. If you call a function like this...
>>> i = 1
>>> inc(i)
...you lose the name which is used to refer to that variable in that
namespace, so although you can get the value and increment it, you
can't rebind it. However... I could be wrong... :)
The closest I can get requires you to pass a stringified version of
the variable. This is still not recommended...
>>> import sys
>>> def inc(var, delta = 1):
... try:
... raise RuntimeError
... except RuntimeError:
... sys.exc_info()[2].tb_frame.f_back.f_locals[var] = \
... sys.exc_info()[2].tb_frame.f_back.f_locals[var] + delta
...
>>> i = 1
>>> inc("i")
>>> i
2
>>> inc("i", 40)
>>> i
42
-----------------------------------------------------------------
Adrian Eyre <a.eyre at optichrome.com> - http://www.optichrome.com
More information about the Python-list
mailing list