简体   繁体   中英

Chaining functions with multiple arguments

Is there a way to chain functions with multiple arguments?

For the moment I "chain" my operation in Python like this:

def createDirIfNecessary(directoryName):
    if not os.path.exists(directoryName):
        print 'Creating directory [%s]'% directoryName
        os.makedirs(directoryName)
    return directoryName

cakeName = 'lemonPie'
cookDate = '2011-01-04'

#yewww very ugly, big blob of function call ...
myDir = os.path.join(getDbDir('kitchenCupboardDir'),'cakes', cakeName)
file  = os.path.join(createDirIfNecessary(myDir), cookDate + '.gz')

For example, in R there is a very elegant way to proceed using a 'pipe' %>% operator (pipe operator also present in Haskell ). The equivalent code is:

cakeName = 'lemonPie'
cookDate = '2011-01-04'

file = getDbDir('kitchenCupboardDir') %>%
         file.path('cakes', cakeName) %>%
         createDirIfNecessary %>%
         file.path(paste0(cookDate,'.gz'))

Here there are only 4 functions, there can be 6, 7 wich can be easily chained. I can't use R unfortunately and I wonder if there is a solution in python 2.7

It is quite related to this topic but with further arguments: Better way to call a chain of functions in python?

The fn package (see on GitHub has the >> operator, and many other nice things for functional programming. You can do functional programming in python, even if ( see also this answer ) it's not really the optimal way. Python can "chain" functions through methods:

file = getDbDir(...).makePath(...).createDir(...).getPath(...)

This is a way to chain operations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM