Python Forum
accessing variables from a decorator
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
accessing variables from a decorator
#1
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?
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  the order of running code in a decorator function akbarza 2 536 Nov-10-2023, 08:09 AM
Last Post: akbarza
  Curious about decorator syntax rjdegraff42 14 2,137 May-03-2023, 01:21 PM
Last Post: rjdegraff42
  ABC Module and @property decorator, Pythonic Way? muzikman 21 5,695 Aug-18-2021, 06:08 PM
Last Post: muzikman
  decorator adamfairhall 0 1,567 Aug-18-2020, 08:38 AM
Last Post: adamfairhall
  Use of @property decorator ruy 16 6,572 Jun-09-2020, 05:29 PM
Last Post: buran
  Decorator staticmethod Use Cases Devarishi 3 2,656 May-20-2019, 04:27 AM
Last Post: Devarishi
  How can we override decorator? bhojendra 2 9,389 May-12-2019, 11:15 PM
Last Post: ichabod801
  Decorator question Dan741 1 2,397 Nov-14-2018, 10:05 AM
Last Post: wavic
  Decorator toy code throws syntax errors kevinxhi 3 3,588 Sep-04-2017, 03:01 AM
Last Post: kevinxhi
  how to make class and instance method (multiple decorator) ? harun2525 7 6,060 May-29-2017, 04:56 PM
Last Post: harun2525

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020