Python Forum
Decorator question - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Decorator question (/thread-14079.html)



Decorator question - Dan741 - Nov-14-2018

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()



RE: Decorator question - wavic - Nov-14-2018

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)