Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Decorator question
#1
Hi,

I have two near identical pieces of code, from practice learning decorators. See below.

My question is, how does decor_with_arg knows that foo is silly_foo? foo is never assigned anything in code. Also, why does 'inside foo' gets printed twice, but 'inside foo 2' gets printed once if both function are called once?

Thanks for the help.

# example 1
    def decor_with_arg(argument):
		def do_something(foo): # <- how does this know what foo is if its never declared?
			print("before foo inside decorator")
			foo()
			print("after foo inside decorator")
			return foo
		return do_something
	
	@decor_with_arg(None)
	def silly_foo():
		print('inside foo')
		
	silly_foo()
		
# example 2
	def decor_2(foo):
		def do_something():
			print("before foo inside decorator 2")
			foo()
			print("after foo inside decorator 2")
			return foo
		return do_something
	
	@decor_2
	def silly_foo2():
		print('inside foo 2')
		
	silly_foo2()
Reply
#2
Because of the function silly_foo is passed as a parameter to the decorator.

Decotaring the function like this:
@decor_with_arg(None)
def silly_foo():
    print('inside foo')
is the same as
def silly_foo():
    print('inside foo')

silly_foo = decor_with_arg(silly_foo)
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  the order of running code in a decorator function akbarza 2 518 Nov-10-2023, 08:09 AM
Last Post: akbarza
  Curious about decorator syntax rjdegraff42 14 2,082 May-03-2023, 01:21 PM
Last Post: rjdegraff42
  ABC Module and @property decorator, Pythonic Way? muzikman 21 5,637 Aug-18-2021, 06:08 PM
Last Post: muzikman
  decorator adamfairhall 0 1,550 Aug-18-2020, 08:38 AM
Last Post: adamfairhall
  Use of @property decorator ruy 16 6,498 Jun-09-2020, 05:29 PM
Last Post: buran
  Decorator staticmethod Use Cases Devarishi 3 2,637 May-20-2019, 04:27 AM
Last Post: Devarishi
  How can we override decorator? bhojendra 2 9,340 May-12-2019, 11:15 PM
Last Post: ichabod801
  Decorator toy code throws syntax errors kevinxhi 3 3,555 Sep-04-2017, 03:01 AM
Last Post: kevinxhi
  accessing variables from a decorator ashwin 1 3,104 Jun-30-2017, 04:11 PM
Last Post: nilamo
  how to make class and instance method (multiple decorator) ? harun2525 7 6,019 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