Hi, I was wondering how I may get a python function to know what its
name is without me having to write it manually? For example:
def func1():
<do some stuff1>
print 'func1'
return True
def func2():
<do some stuff2>
print 'func2'
return True
should be more like
def func1():
<do some stuff 1>
print <self-name>
return True
def func2():
<do some stuff 2>
print <self-name>
return True
I imagine this means things like closures which I'm not familiar with
(I'm not a CS person). In this case, each function is part of a class,
so I imagine I can take a dir() of the class if necessary.
This leads into my next related question, which is How do I get some
sort of macro behavior so I don't have to write the same thing over and
over again, but which is also not neatly rolled up into a function,
such as combining the return statements with a printing of <self-name>?
My application has a bunch of functions that must do different things,
then print out their names, and then each call another function before
returning. I'd like to have the last function call and the return in
one statement, because if I forget to manually type it in, things get
messed up.
(ok, I'm writing a parser and I keep track of the call level with a tab
count, which gets printed before any text messages. So each text
message has a tab count in accordance with how far down the parser is.
Each time a grammar rule is entered or returned from, the tab count
goes up or down. If I mess up and forget to call tabsup() or tabsdn(),
the printing gets messed up. There are a lot of simple cheesy
production rules, [I'm doing this largely as an exercise for myself,
which is why I'm doing this parsing manually], so it's error-prone and
tedious to type tabsup() each time I enter a function, and tabsdn()
each time I return from a function, which may be from several different
flow branches.)
Thanks for any help :)
Michael 3 1203
Michael wrote: def func2(): <do some stuff 2> print <self-name> return True
I imagine this means things like closures which I'm not familiar with (I'm not a CS person). In this case, each function is part of a class, so I imagine I can take a dir() of the class if necessary.
Use the inspect module to find out what you need. This leads into my next related question, which is How do I get some sort of macro behavior so I don't have to write the same thing over and over again, but which is also not neatly rolled up into a function, such as combining the return statements with a printing of <self-name>?
By rolling it up neatly in a function? def printcaller():
print inspect.stack()[1][3]
return True
def func1():
return printcaller()
func1()
func1
True
But remember this prints the name under which the function was created, not
the name of the variable in which it is stored:
func2 = func1 func2()
func1 63*******@sneak email.com wrote: Hi, I was wondering how I may get a python function to know what its name is without me having to write it manually? For example:
def func1(): <do some stuff1> print 'func1' return True
def func2(): <do some stuff2> print 'func2' return True
should be more like def func1(): <do some stuff 1> print <self-name> return True
def func2(): <do some stuff 2> print <self-name> return True
I imagine this means things like closures which I'm not familiar with (I'm not a CS person). In this case, each function is part of a class, so I imagine I can take a dir() of the class if necessary.
Yeah, I think these are closures (though when I learnt CS we didn't get
taught them). Try this:
def makeFunction(na me):
def func():
<do stuff>
print name
return True
return func
func1 = makeFunction('f unc1')
func2 = makeFunction('f unc2') This leads into my next related question, which is How do I get some sort of macro behavior so I don't have to write the same thing over and over again, but which is also not neatly rolled up into a function, such as combining the return statements with a printing of <self-name>?
I think I've answered this too?
Iain 63*******@sneak email.com wrote: How do I get some sort of macro behavior so I don't have to write the same thing over and over again, but which is also not neatly rolled up into a function, such as combining the return statements with a printing of <self-name>?
Decorators: http://www.python.org/peps/pep-0318.html
My application has a bunch of functions that must do different things, then print out their names, and then each call another function before returning. I'd like to have the last function call and the return in one statement, because if I forget to manually type it in, things get messed up.
(ok, I'm writing a parser and I keep track of the call level with a tab count, which gets printed before any text messages. So each text message has a tab count in accordance with how far down the parser is. Each time a grammar rule is entered or returned from, the tab count goes up or down. If I mess up and forget to call tabsup() or tabsdn(), the printing gets messed up. There are a lot of simple cheesy production rules, [I'm doing this largely as an exercise for myself, which is why I'm doing this parsing manually], so it's error-prone and tedious to type tabsup() each time I enter a function, and tabsdn() each time I return from a function, which may be from several different flow branches.)
def track(func):
"""Decorato r to track calls to a set of functions"""
def wrapper(*args, **kwargs):
print " "*track.dep th + func.__name__, args, kwargs or ""
track.depth += 1
result = func(*args, **kwargs)
track.depth -= 1
return result
return wrapper
track.depth = 0
# Then to apply the decorator to a function, e.g.:
def f(x):
return True
# Add this line somewhere after the function definition:
f = track(f)
# Alternately, if you're using Python 2.4 or newer, just define f as:
@track
def f(x):
return True
# Test it:
@track
def fact(n):
"""Factoria l of n, n! = n*(n-1)*(n-2)*...*3*2"""
assert n >= 0
if n < 2:
return 1
return n * fact(n-1)
@track
def comb(n, r):
"""Choose r items from n w/out repetition, n!/(r!*(n-r)!)"""
assert n >= r
return fact(n) / fact(r) / fact(n-r)
print comb(5, 3)
# Output:
"""
comb (5, 3)
fact (5,)
fact (4,)
fact (3,)
fact (2,)
fact (1,)
fact (3,)
fact (2,)
fact (1,)
fact (2,)
fact (1,)
10
"""
--Ben This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Jim Jewett |
last post by:
Normally, I expect a subclass to act in a manner consistent
with its Base classes. In particular, I don't expect to
*lose* any functionality, unless that was the whole point of
the subclass. (e.g., a security-restricted version, or an
interface implementation that doesn't require a filesystem.)
One (common?) exception seems to occur in initialization. I
understand stripping out arguments that your subclass explicitly
handles or...
|
by: Marc |
last post by:
Hi all,
I was using Tkinter.IntVar() to store values from a large list of
parts that I pulled from a list. This is the code to initialize the
instances:
def initVariables(self):
self.e = IntVar()
for part, list in info.masterList.items():
|
by: Ralf W. Grosse-Kunstleve |
last post by:
******************************************************************************
This posting is also available in HTML format:
http://cci.lbl.gov/~rwgk/python/adopt_init_args_2005_07_02.html
******************************************************************************
Hi fellow Python coders,
I often find myself writing::
class grouping:
|
by: David Coffin |
last post by:
I'd like to subclass int to support list access, treating the integer
as if it were a list of bits.
Assigning bits to particular indices involves changing the value of
the integer itself, but changing 'self' obviously just alters the
value of that local variable.
Is there some way for me to change the value of the BitSequence
object itself? I've also tried wrapping and delegating using
__getattr__, but I couldn't figure out how to handle...
|
by: marek.rocki |
last post by:
First of all, please don't flame me immediately. I did browse archives
and didn't see any solution to my problem.
Assume I want to add a method to an object at runtime. Yes, to an
object, not a class - because changing a class would have global
effects and I want to alter a particular object only. The following
approach fails:
class kla:
x = 1
| |
by: Andrew Robert |
last post by:
Hi Everyone,
I am having a problem with a class and hope you can help.
When I try to use the class listed below, I get the statement that self
is not defined.
test=TriggerMessage(data)
var = test.decode(self.qname)
|
by: Peter Maas |
last post by:
The Python FAQ 1.4.5 gives 3 reasons for explicit self (condensed version):
1. Instance variables can be easily distinguished from local variables.
2. A method from a particular class can be called as
baseclass.methodname(self, <argument list>).
3. No need for declarations to disambiguate assignments to local/instance
variables.
|
by: braver |
last post by:
Is there any trick to get rid of having to type the annoying,
character-eating "self." prefix everywhere in a class? Sometimes I
avoid OO just not to deal with its verbosity. In fact, I try to use
Ruby anywhere speed is not crucial especially for @ prefix is better-
looking than self.
But things grow -- is there any metaprogramming tricks or whatnot we
can throw on the self?
Cheers,
|
by: Kurda Yon |
last post by:
Hi,
I found one example which defines the addition of two vectors as a
method of a class. It looks like that:
class Vector:
def __add__(self, other):
data =
for j in range(len(self.data)):
data.append(self.data + other.data)
|
by: Bart Kastermans |
last post by:
I am playing with some trees. In one of the procedures I wrote
for this I am trying to change self to a different tree. A tree
here has four members (val/type/left/right). I found that self = SS
does not work; I have to write self.val = SS.val and the same for
the other members (as shown below). Is there a better way to do this?
In the below self is part of a parse tree, F is the parse tree of a
function f with argument x. If a node...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |