简体   繁体   中英

Python call inner function

I have the following problem:

I have a function that holds another function inside (see code bellow). I need to call the function getFastaEntry with a parameter filename set in the top level function.I tried to call it with generate_fasta_reader(filename).getFastaEntry(), but I get the error message "function object has no attribute getFastaEntry()". Can anybody tell me how I can call the inner function?

def generate_fasta_reader(filename, gzipped=False, strip=True):

    def getFastaEntry():
        filehandle = None

You must return the inner function. It's not accessible otherwise and in fact ceases to exist as soon as the function ends, because there are no references to it at that point. The parameters of the outer function are available to the inner function via a closure. (I assume your actual getFastaEntry() function actually does something besides assign a local variable that goes out of scope almost immediately.)

def generate_fasta_reader(filename, gzipped=False, strip=True):

    def getFastaEntry():
        filehandle = None

    return getFastaEntry

Calling:

getter = generate_fasta_reader("foo.txt")
getter()

Or in one step (if you only need it call the inner function once per outer function call):

generate_fasta_reader("foo.txt")()

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