[Twisted-Python] Coding standard question: flowing long imports with parens

Robert Kern robert.kern at gmail.com
Mon Dec 21 12:27:08 EST 2009

On 2009-12-21 10:10 AM, Glyph Lefkowitz wrote:
> On Dec 21, 2009, at 10:20 AM, James Y Knight wrote:
>> On Dec 21, 2009, at 12:03 AM, Jonathan Lange wrote:
>>> Now that we no longer support Python 2.3, may we also allow imports in
>>> the following style?
>>> from very.long.package import (
>>>    bar,
>>>    foo,
>>>    )
>> Separating "from X import" and "Y" over a newline totally breaks
>> grepping for imported modules. I'd not use it myself, purely because
>> of that, except perhaps when the "Y"s are functions in a module,
>> rather than modules.
> I'm a fan of this style, because it's easier to read and it involves a lot less duplication... at the same time, I can see the 'grep' case.  Anybody want to write a tool which uses the AST to look for name imports?  This would generally be handy anyway :).



grin is a mostly general purpose grepping tool that I wrote, slightly 
specialized for grepping code in VCS checkouts. grinimports.py is an example of 
using it as a library. It uses the AST to normalize import statements. E.g.

   from very.long.package import bar, foo
   import os, sys

turns into

   from very.long.package import bar
   from very.long.package import foo
   import os
   import sys

The grep pattern then runs over the normalized text.

I find this much more robust than grepping the plain text. With all of the 
variations in the import syntax, it's difficult to find a grep pattern that gets 
all of the desired imports and rejects enough of the non-import statements. A 
side effect is that it's easy to get a nice list of all of the import statements 
in your codebase.

   $ grinimports.py --no-color ''

Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco

More information about the Twisted-Python mailing list