Welcome, guest | Sign In | My Account | Store | Cart

This function can extract a inner function from a class or a function. It may be useful when writing a unit test code.

Python, 54 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
__author__ = 'Sunjoong LEE <sunjoong@gmail.com>'
__date__ = '2006-06-20'
__version__ = '1.0.0'

from new import function as mkfunction


def extractFunction(func, name = None):
    """Extract a nested function and make a new one.

    Example1>> def func(arg1, arg2):
                   def sub_func(x, y):
                       if x > 10:
                           return (x < y)
                       else:
                           return (x > y)

                   if sub_func(arg1, arg2):
                       return arg1
                   else:
                       return arg2


               func1 = extractFunction(func, 'sub_func')
               assert(func1(20, 15) == True)


    Example2>> class CL:
                   def __init__(self):
                       pass

                   def cmp(self, x, y):
                       return cmp(x, y)


               cmp1 = extractFunction(Cl.cmp)
    """
    if name == None and repr(type(func)) == "<type 'instancemethod'>":
        new_func = mkfunction(func.func_code, func.func_globals)
        return new_func

    if not hasattr(func, 'func_code'):
        raise ValueError, '%s is not a function.' % func

    code_object = None
    for const in func.func_code.co_consts.__iter__():
        if hasattr(const, 'co_name') and const.co_name == name:
            code_object = const

    if code_object:
        new_func = mkfunction(code_object, func.func_globals)
        return new_func
    else:
        raise ValueError, '%s does not have %s.' % (func, name)

While writing a unit test code, the method to extract a inner function from a class or a function was needed.

It works well but has scope problem. Below is a example not to extract function; ... def func(arg1, arg2): ....... def sub_func(x): ........... if x > 10: ............... return (x < arg2) ... [snip] In above code, arg2 is global variable at sub_func() but local variable at func(). Compair well working example in source code and this.

1 comment

Filippo Squillace 13 years, 4 months ago  # | flag

Wonderful!! Really thanks!

Created by Sunjoong LEE on Mon, 19 Jun 2006 (PSF)
Python recipes (4591)
Sunjoong LEE's recipes (2)

Required Modules

Other Information and Tasks