[SciPy-user] General Python Question: nested function calls

Robert Kern robert.kern@gmail....
Wed Aug 1 14:44:46 CDT 2007


Ryan Krauss wrote:
> I often write code something like this:
> 
> def TruncatePickleFile(pathin, trigname='a', trigtype='sw',
> savepath=None, threshlevel=None, duration=0.05, backup=0.01):
>     """Trunate the pickleddatafile whose path is pathin.  If
>     trigtype=='lg', use a DropDownLightGateTrigger, else use a
>     standard Trigger."""
>     untrunc = pickleddatafiles.PickledDataFile(pathin)
>     mytrunc = pickleddatafiles.TruncateDataObj(untrunc,
> threshlevel=threshlevel, backup=backup, duration=duration)
>     mytrunc.chname = trigname
>     if trigtype == 'lg':
>         mytrunc.SetupTrigger(DataProcMixins.DropDownLightGateTrigger)
>     else:
>         mytrunc.SetupTrigger()
>     mytrunc.SetupTruncChannel()
>     mytrunc.Truncate()
>     pathout = mytrunc.Pickle(savepath)
>     return pathout
> 
> def TruncatePickleFiles(listin, trigname='a', trigtype='sw',
> threshlevel=None, duration=0.05, backup=0.01):
>     listout = []
>     for item in listin:
>         print item
>         curpath = TruncatePickleFile(item, trigname=trigname,
> trigtype=trigtype, threshlevel=threshlevel, duration=duration,
> backup=backup)
>         listout.append(curpath)
>     return listout
> 
> where TruncatePickleFiles is sort of just a vectorization of
> TruncatePickleFile, but with some of the keyword args set.  My problem
> is not that this might not be the fastest way to execute the code, but
> that I get tired of doing this kind of stuff:
> 
> curpath = TruncatePickleFile(item, trigname=trigname,
> trigtype=trigtype, threshlevel=threshlevel, duration=duration,
> backup=backup)
> 
> but I also don't want to just do
> 
> def TruncatePickleFiles(listin, **kwargs):
> 
> because I like to see the defaults and know what keyword arguments are legal.
> 
> Does anyone else have this problem or have an elegant solution to it?
> The problem comes up for me also when I want a derived class to call a
> parent class's method in some partially overwritten method of the
> derived class.
> 
> Ideally, I think I would like to pass **kwargs to the nested function,
> but without using **kwargs in the definition of the top function, if
> that makes any sense.

There isn't really a straightforward solution.

However, for something like this, you may want to consider just implementing one
version of the function which can take either a list of filenames or a single
filename.

-- 
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 SciPy-user mailing list