Create object from variable indirect reference?

Discussion in 'Python' started by NickC, Nov 10, 2009.

  1. NickC

    NickC Guest

    I can't seem to find a way to do something that seems straighforward, so I
    must have a mental block. I want to reference an object indirectly
    through a variable's value.

    Using a library that returns all sorts of information about "something", I
    want to provide the name of the "something" via a variable (command line
    argument). The something is a class in the library and I want to
    instantiate an object of the class so I can start querying it. I can't
    figure out how to pass the name of the class to the library.

    Or, put another way, I can't figure out how to indirectly reference the
    value of the command line argument to create the object.

    To make it clearer, it's roughly equivalent to this in bash:
    Sun="1AU" ; body=Sun; echo ${!body} --> outputs "1AU".

    command line:
    $ ./ephemeris.py Moon

    code:
    import ephem
    import optparse

    # various option parsing (left out for brevity),
    # so variable options.body contains string "Moon",
    # or even "Moon()" if that would make it easier.

    # Want to instantiate an object of class Moon.
    # Direct way:
    moon1 = ephem.Moon()
    # Indirect way from command line with a quasi bashism that obviously fails:
    moon2 = ephem.${!options.body}()

    Can someone point me in the right direction here?

    (The library is PyEphem, an extraordinarily useful library for anyone
    interested in astronomy.)

    Many thanks,

    --
    NickC
    NickC, Nov 10, 2009
    #1
    1. Advertising

  2. NickC

    Jon Clements Guest

    On Nov 10, 2:59 pm, NickC <> wrote:
    > I can't seem to find a way to do something that seems straighforward, so I
    > must have a mental block.  I want to reference an object indirectly
    > through a variable's value.
    >
    > Using a library that returns all sorts of information about "something", I
    > want to provide the name of the "something" via a variable (command line
    > argument).  The something is a class in the library and I want to
    > instantiate an object of the class so I can start querying it.  I can't
    > figure out how to pass the name of the class to the library.
    >
    > Or, put another way, I can't figure out how to indirectly reference the
    > value of the command line argument to create the object.
    >
    > To make it clearer, it's roughly equivalent to this in bash:
    >  Sun="1AU" ; body=Sun; echo ${!body} --> outputs "1AU".
    >
    > command line:
    > $ ./ephemeris.py Moon
    >
    > code:
    > import ephem
    > import optparse
    >
    > # various option parsing (left out for brevity),
    > # so variable options.body contains string "Moon",
    > # or even "Moon()" if that would make it easier.
    >
    > # Want to instantiate an object of class Moon.
    > # Direct way:
    > moon1 = ephem.Moon()
    > # Indirect way from command line with a quasi bashism that obviously fails:
    > moon2 = ephem.${!options.body}()
    >
    > Can someone point me in the right direction here?
    >
    > (The library is PyEphem, an extraordinarily useful library for anyone
    > interested in astronomy.)
    >
    > Many thanks,
    >
    > --
    > NickC


    A direct way is to use:

    moon1 = getattr(ephem, 'Moon')()

    hth
    Jon.
    Jon Clements, Nov 10, 2009
    #2
    1. Advertising

  3. On Tue, 10 Nov 2009 06:59:25 -0800, NickC <>
    wrote:

    > I can't seem to find a way to do something that seems straighforward, so
    > I
    > must have a mental block. I want to reference an object indirectly
    > through a variable's value.
    >
    > Using a library that returns all sorts of information about "something",
    > I
    > want to provide the name of the "something" via a variable (command line
    > argument). The something is a class in the library and I want to
    > instantiate an object of the class so I can start querying it. I can't
    > figure out how to pass the name of the class to the library.
    >
    > Or, put another way, I can't figure out how to indirectly reference the
    > value of the command line argument to create the object.
    >
    > To make it clearer, it's roughly equivalent to this in bash:
    > Sun="1AU" ; body=Sun; echo ${!body} --> outputs "1AU".
    >
    > command line:
    > $ ./ephemeris.py Moon
    >
    > code:
    > import ephem
    > import optparse
    >
    > # various option parsing (left out for brevity),
    > # so variable options.body contains string "Moon",
    > # or even "Moon()" if that would make it easier.
    >
    > # Want to instantiate an object of class Moon.
    > # Direct way:
    > moon1 = ephem.Moon()
    > # Indirect way from command line with a quasi bashism that obviously
    > fails:
    > moon2 = ephem.${!options.body}()
    >
    > Can someone point me in the right direction here?
    >
    > (The library is PyEphem, an extraordinarily useful library for anyone
    > interested in astronomy.)
    >
    > Many thanks,
    >


    Since Python 'variables' are really keys in a namespace dictionary, it's
    fairly straightforward to get at them given a string value -- what you
    probably want in this case is the built-in function getattr()
    (http://www.diveintopython.org/power_of_introspection/getattr.html)...

    So getattr(ephem, "Moon") should give you the class object ephem.Moon,
    which you can then instantiate...



    --
    Rami Chowdhury
    "Never attribute to malice that which can be attributed to stupidity" --
    Hanlon's Razor
    408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)
    Rami Chowdhury, Nov 10, 2009
    #3
  4. NickC <> writes:

    > moon2 = ephem.${!options.body}()


    moon2 = getattr(ephem, options.body)()
    Hrvoje Niksic, Nov 10, 2009
    #4
  5. NickC

    NickC Guest

    Many thanks for the replies. getattr() works great:

    >>> name='Moon'
    >>> m2 = getattr(ephem,name)()
    >>> m2.compute(home)
    >>> print ephem.localtime(m2.rise_time)

    2009-11-11 01:30:36.000002

    shows the moon will rise at 1:30am localtime tonight at my home location.

    Excellent.

    --
    NickC
    NickC, Nov 10, 2009
    #5
  6. NickC

    jhermann Guest

    On 10 Nov., 17:03, NickC <> wrote:
    > Many thanks for the replies.  getattr() works great:


    You can get a little more versatile and even specify the location of
    the name (i.e. the module / package name) without pre-importing it,
    like this...

    def importName(modulename, name=None):
    """ Import identifier C{name} from module C{modulename}.

    If name is omitted, modulename must contain the name after the
    module path, delimited by a colon.

    @param modulename: Fully qualified module name, e.g. C{x.y.z}.
    @param name: Name to import from C{modulename}.
    @return: Requested object.
    @rtype: object
    """
    if name is None:
    modulename, name = modulename.split(':', 1)
    module = __import__(modulename, globals(), {}, [name])
    return getattr(module, name)

    print importName("socket:gethostname")()


    This is especially useful if you want to specify factory classes or
    the like in a non-python config file. The syntax is the same as that
    of setuptools entry points.
    jhermann, Nov 17, 2009
    #6
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. George Ter-Saakov

    Indirect use of COM

    George Ter-Saakov, Aug 26, 2003, in forum: ASP .Net
    Replies:
    2
    Views:
    347
    Natty Gur
    Aug 27, 2003
  2. plaztik via DotNetMonster.com

    Enterprise Library - Indirect/Inherited Configuration??

    plaztik via DotNetMonster.com, May 6, 2005, in forum: ASP .Net
    Replies:
    1
    Views:
    511
    Scott Allen
    May 6, 2005
  3. Yu Lianqing
    Replies:
    1
    Views:
    377
    John Harrison
    Jul 31, 2003
  4. Zachary  Turner

    XSLT indirect variable lookup

    Zachary Turner, May 30, 2007, in forum: XML
    Replies:
    4
    Views:
    765
    Dimitre Novatchev
    Jun 1, 2007
  5. slowpoison

    indirect object notation confusion

    slowpoison, Jun 23, 2005, in forum: Perl Misc
    Replies:
    2
    Views:
    88
    slowpoison
    Jun 23, 2005
Loading...

Share This Page