finding origin of names

Steven Taschuk staschuk at telusplanet.net
Sat Jun 7 14:27:34 EDT 2003


Quoth Robin Becker:
  [...]
> OK I'm being stupid we're importing these things for their value. So I
> really mean to find the original use of the value.
> 
> For the value 1 it's not that obvious, but suppose I create
> 
> #a.py
> red = Color(1,0,0)
> 
> #b.py
> from a import red
> 
> then in derived modules I have a choice to import red from either a or
> b.  Since the b name is imported from a, we can regard the b name as
> derivative for these kinds of constant and therefore prefer to import
> from a (the source of the definition).

Still puzzled, I'm afraid.

If you're writing a module, I see that there can be reasons for
importing an object from one module instead of another, even if
the object is the same in both cases.  In this scenario you just
read the source and/or documentation, and decide yourself where to
import from.

But if you're obtaining a reference to an object on the fly, what
does it matter whether you get it via a.red or b.red, provided
that you get the right object?

And all in all, if you need to look up colours by name, why not
just use a dict mapping from colour name to colour object, rather
than trolling through modules?

My feeling at this point (and with only a limited understanding of
your question) is that the idea of "original defining module" is
not one which Python really acknowledges, and that framing your
problem in such terms will be fighting against the language.

That said, it does occur to me that you could play some tricks
with your own classes:

    # foo.py
    import sys
    class Color(object):
        def __init__(self, r, g, b):
            self.definingmodule = sys._getframe(1).f_globals['__name__']
            # ...
    red = Color(1, 0, 0)

    # bar.py
    from foo import *
    green = Color(0, 1, 0)

    >>> import bar
    >>> bar.green.definingmodule
    'bar'
    >>> bar.red.definingmodule
    'foo'

This is very hackish, though.  I'd first recommend looking for a
more straightforward solution for the underlying problem, whatever
that might be.

-- 
Steven Taschuk                             staschuk at telusplanet.net
"I may be wrong but I'm positive."  -- _Friday_, Robert A. Heinlein





More information about the Python-list mailing list