Skip to content Skip to sidebar Skip to footer

How To Return From With Statement?

I have a function that tries some list of params to connect to ftp and connects to the first server that it could. def connect(params): for user, passw, host in params:

Solution 1:

Maybe move the with statement to outside the connect function?

defconnect(params):
    for user, passw, host in params:
        try:
            import pdb;pdb.set_trace()
            return FTPHost(host, user, passw)
        except FTPError as e:
            logger.debug("Can't connect to ftp error is {}".format(e))
    else:
        raise Exception(
            "Can't connect to ftp server with none of the {}".format(params)
        )

defmain():
    with connect(params) as h:
        do_something(h)

Solution 2:

I would probably convert your connect function into a context manager itself that internally invokes your FTPHost context manager's magic methods:

classFTPConnector:
    def__init__(self, params):
        self.params = params
    def__enter__(self):
        for user, passw, host in params:
            try:
                # import pdb;pdb.set_trace()  # not sure what you want to do with that...
                self.h_context = FTPHost(host, user, passw)
                return self.h_context.__enter__()
            except FTPError as e:
                logger.debug("Can't connect to ftp error is {}".format(e))
        else:
            raise Exception(
                "Can't connect to ftp server with none of the {}".format(params)
            )
    def__exit__(self, exc_type, exc_value, traceback):
        return self.h_context.__exit(exc_type, exc_value, traceback)

Now you could run this in your main function:

withFTPConnector(params) as host:
    host.walk()
    # do something useful with the connection here

# here the connection gets closed again

Post a Comment for "How To Return From With Statement?"