pythonpython-3.xselfpep8pep

Is it a good practice to reassign self properties to a local variable


I wonder if it is a good practice to reassign the status_report to a local variable like this:

def report_remote(remote,error):
            
            def report_error(err):
                if err not in status_report:
                       status_report[err] = []
                status_report[err].append(remote)
            
            status_report = self.status_report
            match error:
                case LookupError():
                    report_error("not_in_list")
                case ConnectionError():
                    report_error("no_connection")

I did that to avoid repeating self many times, but maybe deleting the this makes the code less legible.

Also...

What if the self reference is very large, for example, when the property is a multi-level dictionary and I need data from three levels: self.report['status']['errors']['runtime']?

In this case, would it be a good practice to assign status_report = self.report['status']['errors']['runtime']?"

My main concern is knowing whether I should avoid assigning self properties to local variables, as it might be confusing for other developers


Solution

  • Generally, yes. I myself think it is a good habit to assign status_report = self.report['status']['errors']['runtime']. If you will call self.report['status']['errors']['runtime'] multiple times, and there are so many levels in self.report, the efficiency will be poor for sure as python is an interpreted programming language.

    But, it is not important when you just need to call it once or twice, or it is not sensitive to the cost of time for your program.