Faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

3 of 6 people (50%) answered Yes
Recently 2 of 5 people (40%) answered Yes

Entry

How to obtain an instance's name at runtime?

Sep 15th, 2009 02:20
jick heir, johnny deep, Nathan Wallace, Hans Nowak, Snippet 101, Steven D. Majewski


"""
Packages: miscellaneous.introspection
"""
"""
> > Well, there sort of is a solution, but I don't think you're going
> > to like it. Incidentally, why are you trying to discover this? I'm
> > not a super-meister-coder, but I can't imagine a situation where
> > knowing this would be useful.
> 
> Ok, I knew I was going to look like a dumb camel right after
> posting my question... Nevertheless there is a useful case of
> knowing such an instance's name, at least I believe I found
> one. Have a look at the following page, spot the question mark
> and you'll know what I mean:
> 
>   http://starship.python.net/crew/gherman/UMLgenTest.pdf
> 
> But, PLEASE, don't start to ask me anything about the project
> itself!! It's all in a very pre-pre-pre-alpha phase...
> 
> There might be some workaround solution in oder to get that
> name I want, as in some of the replied in this thread, but
> I'll evaluate that later...
It's easy to get *A* name -- 
 Classes and functions have cannonical names in Python because Python
distinguishes between definition and assignment for classes and
functions. They also have a cannonical namespace -- for classes,
their __module__ attribute, for Python functions, their func_globals
attribute (which is the __dict__ of the __module__ they were defined
in.)  That's why their names are "sticky" . 
 Classes and functions can be aliased and assigned to other names,
but for debugging, tracebacks and printing, you want that cannonical
defining name. 
 There are other types of objects that could benefit from "sticky" 
names: constants and enumns for example. But Python doesn't 
have a different syntax to indicate a definition separate from 
any other assignment. 
You can get a name by searching for the thing in all of the namespaces:
"""
import sys  # added by PSST
def findname(thing):
    for mod in sys.modules.values():
        for name,val in mod.__dict__.items():
            if val is thing : return name 
print findname( sys.stdin )
#'stdin'
print findname( findname )
#'findname'
print findname( lambda x: x+1 )   # anonymous function doesn't have a name 
                # returns None 
xxx = sys.stdin     # alias sys.stdin to another name
print findname( sys.stdin )   # finds *a* name (whichever is first)
#'xxx'
# Try the __name__ attribute first before searching... 
def nameof( THING ):
    return getattr( THING, '__name__', None ) or findname( THING )
print nameof( lambda x: x+1 )
#'<lambda>'
mod = sys
print nameof( mod )
'sys'
 http://www.b2bgrant.com
http://www.pets-online.easyfindindia.com/
http://www.photography.pearlaction.com
http://www.photography.sariskas.com/
http://www.play-web-games.mundawar.com
http://www.realestate.easyfindindia.com/
http://www.real-estate.terrymart.com/
http://www.bigrockwell.com
http://www.schooltime.just2world.com/
http://www.seo-expert.life4style.com
http://www.software.furnimpact.com/
http://www.sports.indiaeduresults.com/
http://www.sports-in-india.easyfindindia.com/
http://www.srjgroup.slots12.com
http://www.teen-life.casinogametown.com/
http://www.top-beauty-tips.rajhealthcenter.com
http://www.travel.buxorgroup.com/
http://www.travel-guide.easyfindindia.com/
http://www.rockwellentertainments.com/
http://www.vehicles.realmaxor.com/
http://www.video-games.khairthal.com/
http://www.visual-arts.lgfsolution.com/
http://www.jforjewel.com
http://www.watch-online-free-cricket-match.indiatourpoint.com
http://www.weddings.furnimpact.com/
http://www.organizations.alwarmall.com/
http://www.Pet-for-Sale.jforjewel.com
http://www.pets.jestrugs.com/
http://www.office-products.sariskas.com/
http://www.pets.logicdunia.com/
http://www.propertybunch.com
http://www.buxorgroup.com
http://www.gsmrainbow.com
http://www.lgfsolution.com
http://www.nightroutes.com
http://www.monilek.com
http://www.mobile-computing.lgfsolution.com/
http://www.movies.promotioncrown.com/
http://www.music.a1start.com/
http://www.news-and-media.srplanet.com/
"""
[1] You could do a smarter seach of the name space, but I'm not sure
if that would be any better for your application.
[2] You could also append the module name to the name and return 
  "sys.stdin" rather than "stdin" above. 
[3] Might there be cases where you want the '__repr__' rather than
 the name ?  i.e. "<open file '<stdin>', mode 'r' at 5a28500>" rather
 than "stdin" 
"""
http://sundhedernaeringguide.blogspot.com/
http://zdravevyzivypruvodce.blogspot.com/
http://guidasalutenutrizione.blogspot.com/
http://gesundheiternahrungpflege.blogspot.com/
http://soinssantenutrition.blogspot.com/
http://zdravljeprehranavodic.blogspot.com/
http://healthnutritionhoito.blogspot.com/
http://hlhnutgr.blogspot.com/
http://gezondheidvoedinggids.blogspot.com/
http://taplalkozas-egeszsegugyikezikonyv.blogspot.com/
http://hlthnutbg.blogspot.com/