Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #5550

Re: indirect assignment question

References <4DD203F1.1000202@gmail.com>
Date 2011-05-16 22:24 -0700
Subject Re: indirect assignment question
From Chris Rebert <clp2@rebertia.com>
Newsgroups comp.lang.python
Message-ID <mailman.1658.1305609877.9059.python-list@python.org> (permalink)

Show all headers | View raw


On Mon, May 16, 2011 at 10:13 PM, Andy Baxter <highfellow@gmail.com> wrote:
> Hi,
>
> I have some lines of code which currently look like this:
>
>      self.window = self.wTree.get_widget("mainWindow")
>      self.outputToggleMenu = self.wTree.get_widget("menuitem_output_on")
>      self.outputToggleButton = self.wTree.get_widget("button_toggle_output")
>      self.logView = self.wTree.get_widget("textview_log")
>      self.logScrollWindow = self.wTree.get_widget("scrolledwindow_log")
>
> and I would like (for tidiness / compactness's sake) to replace them with
> something like this:
>        widgetDic = {
>           "mainWindow": self.window,
>           "menuitem_output_on": self.outputToggleMenu,
>           "button_toggle_output": self.outputToggleButton,
>           "textview_log": self.logView,
>           "scrolledwindow_log": self.logScrollWindow
>        }
>        for key in widgetDic:
>           ... set the variable in dic[key] to point to
> self.wTree.get_widget(key) somehow
>
> what I need is some kind of indirect assignment where I can assign to a
> variable whose name is referenced in a dictionary value.
>
> Is there a way of doing this in python?

You can achieve almost the same level of brevity, with less use of
magic, by simply using a local variable to refer to
self.wTree.get_widget:

w = self.wTree.get_widget # or choose some other similarly short variable name
self.window = w("mainWindow")
self.outputToggleMenu = w("menuitem_output_on")
self.outputToggleButton = w("button_toggle_output")
self.logView = w("textview_log")
self.logScrollWindow = w("scrolledwindow_log")

Python functions/methods are first-class; exploit this feature!

Cheers,
Chris
--
http://rebertia.com

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: indirect assignment question Chris Rebert <clp2@rebertia.com> - 2011-05-16 22:24 -0700

csiph-web