making a variable available in a function from decorator

  • Thread starter Bruno Desthuilliers
  • Start date
B

Bruno Desthuilliers

Evan Klitzke a écrit :
Sort of. Functions are objects in python, so you can set attribute on them. E.g.

def foo():
return foo.c

foo.c = 1
print foo()
.... print foo.c
....Traceback (most recent call last):
File "<stdin>", line 1, in ?
File said:
Which will print 1. Of course, it would generally be better to write
your own class for this sort of thing, so that you can set the
variable in the instance scope.

Indeed. But even with OO, explicit is better than implicit.
 
R

rkmr.em

Hi
I create a variable in a decorator. i want to be able to access that
variable in the function to be decorated. How to do this?
thanks
 
M

Marc 'BlackJack' Rintsch

I create a variable in a decorator. i want to be able to access that
variable in the function to be decorated. How to do this?

Pass it as argument to the function:

def deco(func):
eggs = 42
def decorated(*args, **kwargs):
kwargs['spam'] = eggs
func(*args, **kwargs)
return decorated

@deco
def test(parrot, spam):
print parrot, spam

Ciao,
Marc 'BlackJack' Rintsch
 
R

rkmr.em

is it possible to do this without passing it as a function argument?

I create a variable in a decorator. i want to be able to access that
variable in the function to be decorated. How to do this?

Pass it as argument to the function:

def deco(func):
eggs = 42
def decorated(*args, **kwargs):
kwargs['spam'] = eggs
func(*args, **kwargs)
return decorated

@deco
def test(parrot, spam):
print parrot, spam

Ciao,
Marc 'BlackJack' Rintsch
 
B

Bruno Desthuilliers

(e-mail address removed) a écrit :
(top-post corrected)
>
Pass it as argument to the function:

def deco(func):
eggs = 42
def decorated(*args, **kwargs):
kwargs['spam'] = eggs
func(*args, **kwargs)
return decorated

@deco
def test(parrot, spam):
print parrot, spam
> is it possible to do this without passing it as a function argument?

What's your use case, exactly ? Having a function depending on a name
being set by a decorator is not exactly pythonic, and arguments are
meant to pass variables to functions...
 
E

Evan Klitzke

is it possible to do this without passing it as a function argument?

Sort of. Functions are objects in python, so you can set attribute on them. E.g.

def foo():
return foo.c

foo.c = 1
print foo()

Which will print 1. Of course, it would generally be better to write
your own class for this sort of thing, so that you can set the
variable in the instance scope.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top