Skip to content

Instantly share code, notes, and snippets.

@Ceasar
Last active December 14, 2015 04:28
Show Gist options
  • Save Ceasar/5027942 to your computer and use it in GitHub Desktop.
Save Ceasar/5027942 to your computer and use it in GitHub Desktop.
Experiments with scope in Python.
"""
Python scope is not dynamic.
"""
def foo():
print x
x = 0
def bar(func):
x = 1
func()
foo() # prints 0
bar(foo) # prints 0
"""
Non-global variables that are in scope are strictly read-only.
In Python 3, this restriction is removed via the `nonlocal` keyword.
"""
x = 10
def foo():
global x
x += 5
print x
foo() # prints 15
def bar():
x = 10
def foobar():
# global x # uncommenting this line doesn't help
x += 5
print x
foobar()
bar() # causes "UnboundLocalError: local variable 'x' referenced before assignment"
def car():
print car
car() # prints <function car at 0x...>
def dar():
dar = 1
print dar
dar() # prints 1
ear = 1
def ear():
print ear
ear() # prints <function ear at 0x...>
def far():
far = far
print far
far() # UnboundLocalError: local variable 'far' referenced before assignment
def enclosing_function():
def factorial(n):
if n < 2:
return 1
return n * factorial(n - 1) # does not fail with NameError
print factorial(5)
enclosing_function() # prints 120
import functools
import time
class TimeoutException(Exception):
pass
def retry(exceptions, truncate=5, delay=0.25):
"""Retry the decorated function using an exponential backoff strategy.
If the function does not complete successfully a TimeoutException is
raised."""
def wrapper(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
tries = 0
while tries < truncate:
try:
return func(*args, **kwargs)
except exceptions, e:
print "%s, Retrying in %d seconds..." % (str(e), delay)
time.sleep(delay)
delay += delay # W804 local variable 'delay' (defined in enclosing scope on line 9) referenced before assignment
tries += 1
else:
raise TimeoutException()
return wrapped
return wrapper
@Ceasar
Copy link
Author

Ceasar commented Feb 25, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment