[Tutor] a query
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Sun, 11 Aug 2002 19:44:16 -0700 (PDT)
On 8 Aug 2002, Avinash Dutta wrote:
> is it possible to call a function B() which is defined inside another
> function A() from the scope of another function C() in python?
When we define an function inside another, we can treat it as if it were a
local variable --- it'll only be accessible from A(). So unless you
return that 'B' function from A(), we shouldn't be able to touch B.
> def A():
> ----def B():
>
> def x():
>
> def C():
> ----# how can i call B() from here.
This isn't possible directly, because 'B' is a local function of A, that
is, it's a local name as far as Python's concerned.
However, we can do something like this:
###
>>> def makeIncrementer(n):
... def inc(x):
... return x + n
... return inc
...
>>> inc_by_one = makeIncrementer(1)
>>> inc_by_one(42)
43
>>> makeIncrementer("world")("hello")
'helloworld'
###
(I'm sorry about the last example; I just couldn't resist. *grin*)
What are you trying to do with inner functions, though? There may be a
more Pythonic way of approaching your problem.
Hope this helps!