Options

Python WTF - somewhat advanced. [LOCK]

DocDoc Registered User, ClubPA regular
edited April 2010 in Help / Advice Forum
Challenge - figure out why this python code doesn't work.
foo = None

def get_tags(func):
    def wrapper(*args, **kwargs):
        print foo
        if foo is None: foo = {'a':1}
        return func(*args, **kwargs)
    return wrapper

@get_tags
def test():
    print 'test'

test()

This code works:
foo = None

def get_tags(func):
    def wrapper(*args, **kwargs):
        print foo
        #if foo is None: foo = {'a':1}
        return func(*args, **kwargs)
    return wrapper

@get_tags
def test():
    print 'test'

test()

The tricky thing is that it fails at the print statement in the first one, and I've only commented out the line AFTER the print statement on the second one.

Did I discover a bug in python2.6 or something?


Update: this works -
foo = None

def decor(func):
    def wrapper(*args, **kwargs):
        print foo
        if foo is None: a =1 
        return func(*args, **kwargs)
    return wrapper

@decor
def test():
    print 'test'

test()

so I'm pretty sure it thinks foo is supposed to be in the local scope. Trying some fixes...

woo, solved it myself.



THANKS GUYS

Doc on
Sign In or Register to comment.