Jan-05-2024, 01:23 PM
(This post was last modified: Jan-05-2024, 01:24 PM by Gribouillis.)
(Jan-05-2024, 11:25 AM)blobdx7 Wrote: But, anyway, is this a correct usage of the keyword global?Normally people try to avoid the
global
keyword by not assigning to global variables, and when they use it they tend to minimize the number of variables using global
. This is normally achieved by encapsulating variables in classes. Here is how you could write the same code without this keyword by introducing a FtpUser class for examplefrom ftplib import FTP import os import configparser class FtpUser: def __init__(self, address, name, password): self.address = address self.name = name self.password = password def download_all(self, localPath): ftp = FTP(self.address) ftp.login(user=self.name, passwd=self.password) ftpFileNames = ftp.nlst() for ftpfileName in ftpFileNames: if not isDir(ftp, ftpfileName): localFileName = os.path.join(localPath, ftpfileName) localFile = open(localFileName, "wb") ftp.retrbinary("RETR " + ftpfileName, localFile.write, 1024) localFile.close() ftp.quit() def __repr__(self): return f"{type(self).__name__}({self.address!r}, {self.name!r}, {self.password!r})" @classmethod def from_init_file(cls, parametersFileName, section="myvars"): config = configparser.ConfigParser() config.read(parametersFileName) return cls( config.get(section, "ftpAddress"), config.get(section, "ftpUserName"), config.get(section, "ftpPassword"), )
import my_ftp ftp_user = my_ftp.FtpUser.from_init_file("C:\\Users\\Python\\config.ini") print(ftp_user) # here i'm checking if the variable's value are ok ftp_user.download_all("C:\\Users\\Python\\")As a bonus, this code allows you to enter several ftp addresses and users in the config file under different section names.
Read PEP 8 to learn about variables and functions naming conventions usually chosen in Python code.
« We can solve any problem by introducing an extra level of indirection »