Search code examples
pythonglobaltry-except

Python try except not using imported variable


Imported module, connection_status_message.py:

connection_status_message = "Not Connected"

Try Except file, connect_to_server.py:

from Server.connection_status_message import connection_status_message

def connect_to_server(host,user,password):
    try:
        connect(host,user,password)
    except NoConnection:
        connection_status_message = "Could not reach host..."
        return
...

The issue is the variable is trying to be made local. So I read up on the issue and saw how to reference a global variable:

def connect_to_server(host,user,password):
    try:
        connect(host,user,password)
    except NoConnection:
        global connection_status_message
        connection_status_message = "Could not reach host..."
        return
...

But now PyCharm is stating the import statement at the top is no longer being used.

How can I get this Try/Except to use the imported variable?


Solution

  • I couldn't replicate your issue, but if your import line is stored under a function, the variable is nonlocal instead of global:

    def connect_to_server(host,user,password):
        try:
            connect(host,user,password)
        except NoConnection:
            nonlocal connection_status_message
            connection_status_message = "Could not reach host..."
    

    Another way is to not load the variable directly into your namespace so you have reference of where it came from to avoid local variables being created:

    from Server import connection_status_message as csm
    csm.connection_status_message
    
    # "No Connection"
    
    def func():    
        csm.connection_status_message = "Could not reach host..."
    
    csm.connection_status_message
    
    # "Could not reach host..."
    

    You might also consider creating a class to handle all these as an object:

    class Connection(object):
        def __init__(self):
            self.connection_status_message = "No Connection"
            # TODO: initialize your class
    
        def connect(self, host, user, password):
            # TODO code connect criteria stuff here
    
        def connect_to_server(self, host, user, password):
            try:
                self.connect(host,user,password)
            except NoConnection:
                self.connection_status_message = "Could not reach host..."
                # ... return whatever ...#
    

    Now you can do from Server import Connection and create a local Connection object to manipulate:

    conn = Connection()
    conn.connect_to_server(host, user, password)
    

    This might be obvious, but in any case the value is only stored in memory during this execution. The actual connection_status_message.py is never updated with this value.