访问包装函数属性时的Python 3 UnboundLocalError

时间:2015-03-12 14:30:59

标签: python variables python-3.x scope runtime-error

我实现了一个调试函数来测量执行方法所需的时间。 出于某种原因,我在访问UnboundLocalError: local variable 'ident' referenced before assignment中的相应名称时获得了measure()

def time(func_or_id, func=None):
    """Decorator to measure time

    Usage:
        @time
        def my_method():
            ...

    or with a specific identifier:
        @time('my_identifier')
        def my_method():
            ...

    or with a uuid:
        @time(True)
        def my_method():
            ...
    """
    ident = None
    uuid_flag = False

    if func is None:
        func = func_or_id
    elif func_or_id is True:
        uuid_flag = True
    else:
        ident = str(func_or_id)

    try:
        fname = func.__name__
    except AttributeError:
        fname = 'Unknown function'

    def measure(*args, **kwargs):
        """Measure time that a function takes to run"""
        if uuid_flag:
            ident = str(uuid4())
        if ident:    # <- Causes the exception!
            fname = ' '.join(fname, ''.join(['(', ident, ')']))
        print('Starting to measure time of:', fname)
        start = datetime.now()
        result = func(*args, **kwargs)
        duration = datetime.now() - start
        print(fname, 'took:', duration)
        return result

    return measure

我不明白为什么会发生这种情况,因为在uuid_flag之后声明的ident检查不会导致任何问题:

def time(func_or_id, func=None):
    """Decorator to measure time

    Usage:
        @time
        def my_method():
            ...

    or with a specific identifier:
        @time('my_identifier')
        def my_method():
            ...

    or with a uuid:
        @time(True)
        def my_method():
            ...
    """
    #ident = None
    uuid_flag = False

    if func is None:
        func = func_or_id
    elif func_or_id is True:
        uuid_flag = True
    #else:
    #    ident = str(func_or_id)

    try:
        fname = func.__name__
    except AttributeError:
        fname = 'Unknown function'

    def measure(*args, **kwargs):
        """Measure time that a function takes to run"""
        if uuid_flag:
            ident = str(uuid4())
        #if ident:
        #    fname = ' '.join(fname, ''.join(['(', ident, ')']))
        print('Starting to measure time of:', fname)
        start = datetime.now()
        result = func(*args, **kwargs)
        duration = datetime.now() - start
        print(fname, 'took:', duration)
        return result

    return measure

访问ident时我做错了什么?

0 个答案:

没有答案