Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic

Duncan Booth duncan.booth at invalid.invalid
Sat Apr 14 08:06:36 EDT 2007


James Stroud <jstroud at mbi.ucla.edu> wrote:
> I like this one for some reason. Just the "using self" would save
> hella typing in a lot of classes. I would favor a convention with
> leading dots to disambiguate from other variables. This wouldn't
> conflict with, say, floats, because variable names can't begin with a
> number. 

I can't see how it is going to save you any typing over what you can
already do. 

The suggested example:

 self.setFixedSize(200, 120)
 self.quit = QtGui.QPushButton("Quit", self)
 self.quit.setGeometry(62, 40, 75, 30)
 self.quit.setFont(QtGui.QFont("Times", 18, QtGui.QFont.Bold))
 self.connect(self.quit, QtCore.SIGNAL("clicked()"), QtGui.qApp,
 QtCore.SLOT("quit()"))

(259 characters including newlines but not leading indents).

would become:

 using self:
     .setFixedSize(200,120)
     .quit = QtGui.QPushButton("Quit", self)
     using quit:
         .setGeometry(62, 40, 75, 30)
         .setFont(QtGui.QFont("Times", 18, QtGui.QFont.Bold))
     .connect(self.quit, QtCore.SIGNAL("clicked()"), QtGui.qApp, QtCore.SLOT("quit()"))

(251 characters including newlines but not leading indents).

If you are going to reference self.quit a lot of times then it makes
sense to also assign it to a local variable and then you already get 
even fewer characters (239):

self.setFixedSize(200, 120)
q = self.quit = QtGui.QPushButton("Quit", self)
q.setGeometry(62, 40, 75, 30)
f = QtGui.QFont
q.setFont(f("Times", 18, f.Bold))
self.connect(q, QtCore.SIGNAL("clicked()"), QtGui.qApp, QtCore.SLOT("quit()"))

Assigning 's=self' would save even more typing, but there are limits 
to how unreadable you want it.

Using local variables also means you don't have any ambiguity and can 
use a variety of such shorthands interchangeably (e.g. q and f above).



More information about the Python-list mailing list