Python Forum

Full Version: accessing variables from a decorator
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have code similar to this
def my_function_decorator(f):
	def wrap(*args, **kwargs):
		my_count_variable = 1
		return f(*args, **kwargs)
	return wrap

@my_function_decorator
def my_decorated_function():
	pass
is there any way i can access my_count_variable from inside my_decorated_function? and even if i can is this good practice that can scale well?
You can access it if you pass it. Or if you keep the variable in an enclosing scope that the function can reach into (like a class).

What do you consider to "scale well"? You're not consuming excess memory since it's just one variable regardless of however much you call that function.