Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does python optimize unused variables out?

Tags:

python

my linter constantly bugs me with unused variable warning, for the following class that I have created:

class LockGuard(object):
    def __init__(self, mutex):
        self.mutex = mutex
        self.mutex.acquire()

    def __del__(self):
        self.mutex.release()

in code, I get the warning everytime I use this

def do_something(self)
    locker = LockGuard(self.mutex)
    // do something on the data
    return outcome

I know that c++ compilers optimize unused variables out, I was wondering if python ever does the same? Therefore remove the lock on data.

like image 417
apramc Avatar asked Dec 03 '22 11:12

apramc


1 Answers

The linter should bug you about this. Because the correct way to manage context is with a context manager.

with LockGuard():
    # do stuff

Put the implementation details of how to acquire and release a lock into LockGuard.__enter__ and LockGuard.__exit__ respectively.

You should not rely on __init__ and __del__ for this, because __del__ is not reliable.

I know that C++ compilers optimize unused variables out, I was wondering if Python ever does the same? Therefore remove the lock on data.

Python will not do the same. There are some peephole optimizations, but nothing so drastic as removing an object from scope entirely. Once the reference count of an instance falls to zero (i.e. once locker name goes out of scope), it should be deleted, but there is no guarantee in the implementation about when this happens and there is not even a guarantee that a custom __del__ will be called at all.

like image 67
wim Avatar answered Dec 21 '22 06:12

wim