2

I have this python 3 code:

with next(val for key,val in MyServer.my_dict.items() if 'AS1' in key) as AS:
    AS.port = 80
    AS.connect()
    ...

I am getting an 'AttributeError:__enter__'. What does this mean? Is there a reason this will not work? Or is there a better way to do this?

EDIT: I found THIS, which appears to be the answer. I just added the __enter__ and __exit__ methods after the __init__ of Server (the class of MyServer), and it worked:

class Server:
    """Base server class"""
    def __init__(self, ip_addr, port, username, password):
        self.ip_addr = ip_addr
        self.port = port
        self.user = username
        self.p_word = password
        self.name = 'Generic Server'
    def __enter__(self):
        return self
    def __exit__(self, type, value, traceback):
        pass

Is there something else I need to do? Is that it?

lukehawk
  • 1,423
  • 3
  • 22
  • 48
  • 1
    `with` is not a substitute for assigning values. It is used specifically with objects that implement an `__enter__` and `__exit__` method (such as file objects). – cs95 Oct 24 '18 at 20:46
  • Thanks - it looks like it could make sense though, to use it in this context though, right? Since it is meant to handle the ... cleanup and what not? Since I am using it to connect to a server, and when I am done with the with, I would like it to close the connection, clear whatever memory, yada yada yada. (Though I realize now I need to add that 'cleanup' to my `__exit__` method, right?) – lukehawk Oct 24 '18 at 20:51
  • Yeah, that's enough – cs95 Oct 24 '18 at 20:54

0 Answers0