Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

let's say we have two functions:

def ftpConnect(): 
    ftp = FTP('server')
    ftp.login()
    ftp.cwd('/path')

def getFileList():
    ftpConnect()
    files = ftp.nlst()
    print(files)

If I call the getFileList() function it won't work because it doesn't know the ftp var.

I know that if I declare the ftp variable inside ftpConnect() function as global it will work, but I was wondering if there is a better / more elegant way of doing it.

share|improve this question

3 Answers 3

up vote 1 down vote accepted

In my opinion, the most elegant solution would be to make a FTP-class, which would have the ftp-variable as a private attribute.

class FTPConnection(object):
    def __init__(self, server):
        self._ftp = FTP(server)

    def connect(self): 
       self._ftp.login()
       self._ftp.cwd('/path')


    def getFileList():
        files = self._ftp.nlst()
        print(files)

ftp = FTPConnection('server')
ftp.connect()
ftp.getFileList()
share|improve this answer
    
Seems like a good idea, but the name of the class is misleading. –  Matthias Jul 10 '13 at 15:02

Functions can return values. Return values are cool!

Return ftp from ftpConnect():

def ftpConnect(): 
    ftp = FTP('server')
    ftp.login()
    ftp.cwd('/path')
    # return the value of `ftp` to the caller
    return ftp

def getFileList():
    # assign the return value of `ftpConnect` to a new local variable
    ftp = ftpConnect()
    files = ftp.nlst()
    print(ftp.nlst())

You may also want to look in to object-oriented programming techniques; define a class that handles all your FTP-related operations, and store the FTP server connection as an attribute of the instance.

share|improve this answer
    
Your edit made your answer exactly same as mine. –  Ashwini Chaudhary Jul 10 '13 at 14:44
3  
I misread the code at first, then edited it; if we ended up with the same code then that's because we are both awesome. –  Martijn Pieters Jul 10 '13 at 14:45
    
Great minds think alike. –  Matthias Jul 10 '13 at 15:01

Return ftp from ftpConnect() and assign the return value to a variable named ftp:

def ftpConnect(): 
    ftp = FTP('server')
    ftp.login()
    ftp.cwd('/path')
    return ftp         #return ftp from here

def getFileList():
    ftp = ftpConnect() # assign the returned value from the
                       # function call to a variable
    files = ftp.nlst()
    print(ftp.nlst())
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.