Accessing nested functions for testing
Gerrit Holl
gerrit at nl.linux.org
Tue May 20 16:20:48 EDT 2003
Chad Netzer schreef op dinsdag 20 mei om 20:40:33 +0000:
> Is there any way to access a nested function as though it were not
> nested (ie. for testing it directly)?
>
> For example:
>
> def foo():
> def bar():
> pass
> bar()
>
> Is it possible to execute bar from outside of foo? I can't even find a
> way to see or access bar at all, from the global scope.
>
> My intuition says this is not possible, I'm just curious if that is
> truly the case.
It is possible, but not Beatiful:
81 >>> def foo():
81 ... def sub1():
81 ... def subsub1(): pass
81 ... def subsub2(): pass
81 ... def sub2(): pass
81 ... def sub3(): pass
81 ...
82 >>> foo.func_code.co_consts
(None, <code object sub1 at 0x400ce020, file "<stdin>", line 2>, <code object sub2 at 0x400ce060, file "<stdin>", line 5>, <code object sub3 at 0x400ce0a0, file "<stdin>", line 6>)
85 >>> import types
86 >>> [c for c in foo.func_code.co_consts if isinstance(c, types.CodeType)]
[<code object sub1 at 0x400ce020, file "<stdin>", line 2>, <code object sub2 at 0x400ce060, file "<stdin>", line 5>, <code object sub3 at 0x400ce0a0, file "<stdin>", line 6>]
88 >>> [c for c in foo.func_code.co_consts if isinstance(c, types.CodeType)][0].co_name
'sub1'
89 >>> [c for c in foo.func_code.co_consts if isinstance(c, types.CodeType)][1].co_name
'sub2'
90 >>> [c for c in foo.func_code.co_consts if isinstance(c, types.CodeType)][1]
<code object sub2 at 0x400ce060, file "<stdin>", line 5>
91 >>> exec [c for c in foo.func_code.co_consts if isinstance(c, types.CodeType)][1]
(executed)
yours,
Gerrit.
--
282. If a slave say to his master: "You are not my master," if they
-- Hammurabi, Code of Law
--
Asperger Syndroom - een persoonlijke benadering:
http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
http://www.sp.nl/
More information about the Python-list
mailing list