Decorators without function

V

Vedran

Hello!

Is it possible to apply a decorator on a block of code, without defining
a function that decorator is applied to.

I have to generate a lot of similar graphs. For that reason I use
plot_decorator to perform usual figure setup(outfile, legend, x_label,
y_label and so on), and pylab.plot commands to do the actual plotting.

Current solution:

@plot_decorator(fig_params1)
def plt():
pylab.plot(..first graph data...)
pylab.plot(..second graph data..)
plt()

Is it possible to apply decorator only to the body of plt (several
pylab.plot commands) without actually defining this function, because I
use it only once, right after the definition?
 
P

Peter Otten

Vedran said:
Hello!

Is it possible to apply a decorator on a block of code, without defining
a function that decorator is applied to.

You can only decorate functions or classes.
I have to generate a lot of similar graphs. For that reason I use
plot_decorator to perform usual figure setup(outfile, legend, x_label,
y_label and so on), and pylab.plot commands to do the actual plotting.

Current solution:

@plot_decorator(fig_params1)
def plt():
pylab.plot(..first graph data...)
pylab.plot(..second graph data..)
plt()

Is it possible to apply decorator only to the body of plt (several
pylab.plot commands) without actually defining this function, because I
use it only once, right after the definition?

I have a hunch that a contextmanager is a better match for your
requirements, see

http://docs.python.org/library/contextlib.html#contextlib.contextmanager

Peter
 
G

Gregory Ewing

Vedran said:
@plot_decorator(fig_params1)
def plt():
pylab.plot(..first graph data...)
pylab.plot(..second graph data..)
plt()

You could do something like

def call(f):
f()

@call
@plot_decorator(fig_params1)
def plt():
pylab.plot(..first graph data...)
pylab.plot(..second graph data..)
 

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

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top