memoize IDs

Hi Julian,
Sorry for missing your original posting...
I think this is what I could use. I like not having extra lines !
How about using __getattr__ instead of __getitem__
Then you wouldn't even need the brackets and no parenthesis...
Then one could say e.g.
ID.about and ID.exit
if you had
   ID = IdDict()
at the end of your module and
  from module import ID
in each module where ever you need IDs
((This last idea is still somewhat broken, because you would want to be able
to reuse names like ID.exit in separate modules / classes ... I can't think
of a good solution to this right now...))

- Sebastian

···

On Thursday 17 November 2005 02:30, Julian Snitow wrote:

Hello all,

I was going through the "Getting Started" section in the wxpython wiki
and noticed a lot of this:

ID_ABOUT=101
ID_EXIT=110 # note that ID_* = NewId() would still require these
lines # ... etc.

I, wxpython newb though I may be, humbly offer the following module,
which should render that practice obsolete.

Julian

### wxhelper.py
## Usage:
##
## from wxhelper import wxid
##
## doSomething(wxid["about"], ...)
## doSomethingElse(wxid["about"], ...) # same id as before

from wx import NewId

class IdDict:

    """
    A read-only "dictionary" that interns its inputs
    with wxWidgets NewId()s.
    """

    def __init__(self):
        self.dict = {}

    def __getitem__(self, key):
        """
        Ensure that each key returns a single, unique
        wx ID throughout the program
        """
        val = None
        try:
            val = self.dict[key]
        except KeyError:
            val = self.dict[key] = NewId()

        return val

    def __setitem__(self, key, item):
        raise TypeError, "object does not support item assignment"

wxid = IdDict()

if __name__ == "__main__":
    print 'wxid["about"] =', wxid["about"]
    print 'wxid["exit"] =', wxid["exit"]

    # again to demonstrate sameness
    print 'wxid["about"] =', wxid["about"]
    print 'wxid["exit"] =', wxid["exit"]

### /wxhelper.py

---------------------------------------------------------------------
To unsubscribe, e-mail: wxPython-users-unsubscribe@lists.wxwidgets.org
For additional commands, e-mail: wxPython-users-help@lists.wxwidgets.org