[Python-Dev] Syntax suggestion for imports

Scott Dial scott+python-dev at scottdial.com
Fri Jan 4 09:48:38 CET 2008


Jeroen Ruigrok van der Werven wrote:
> [Half tongue-in-cheek]
> 
> -On [20080104 08:04], Drew Perttula (drewp at bigasterisk.com) wrote:
>> When I saw the OP, I actually wondered why people whose codebases are 
>> "filled" with the same try/except block over and over hadn't just 
>> written their own import_with_alternative function in the first place. 
> 
> Because you would have to import it as well in order to use it? ;)
> 

The keyphrase was "people whose codebases are 'filled' with ..." If they 
are maintaining a codebase, then I am sure adding one utility function 
to their library would be trivial. Or if you have enough of them in one 
file.. dedicating 7 lines of code for:

def import_any(*names):
     for name in names:
         try:
             return __import__(name)
         except StandardError:
             pass
     raise ImportError('no importable names')

, seems like a bargain for readability. Or to include the "None" case 
that people have brought up, we can spare 2 more lines:

def import_any(*names, **kwargs):
     required = kwargs.get('required', True)
     for name in names:
         try:
             return __import__(name)
         except StandardError:
             pass
     if required:
         raise ImportError('no importable names')

If nothing else, writing this email will remind me to avoid this 
try/except pattern in future codebases, if I have more than 1 instance 
of it (right about the break even point).

-Scott

-- 
Scott Dial
scott at scottdial.com
scodial at cs.indiana.edu


More information about the Python-Dev mailing list