Why do directly imported variables behave differently than those attached to imported module?

Daniel Kluev dan.kluev at gmail.com
Tue May 3 15:55:04 EDT 2011


On Wed, May 4, 2011 at 6:23 AM, Dun Peal <dunpealer at gmail.com> wrote:
> P.S. now I have to ask: is there a symbolic reference in Python, i.e.
> a name foo that points to "whatever bar.baz is pointing at"?

Well, you could easily simulate that with proxy object,
class SymbolicReference(object):
    def __init__(self, ns, name):
        self.__ns = ns
        self.__name = name

    def __get(self):
        return self.__ns[self.__name]

    def __getattribute__(self, attr):
        try:
            return object.__getattribute__(self, attr)
        except:
            return self.__get().__getattribute__(attr)

    def __repr__(self):
        return self.__get().__repr__()

    def __str__(self):
        return self.__get().__str__()

>>> a = 1
>>> b = SymbolicReference(globals(), 'a')
>>> b
1
>>> a = 10
>>> b
10


-- 
With best regards,
Daniel Kluev



More information about the Python-list mailing list