[Python] Chaining functions with multiple arguments

Discussão em 'Python' iniciado por Stack, Agosto 6, 2025.

  1. Stack

    Stack Membro Participativo

    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 which 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?

    Continue reading...

Compartilhe esta Página