Does python optimize unused variables?

my linter constantly scares me with an unused variable warning for the following class that I created:

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

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

in code, I get a warning every time 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, I was wondering if python ever does the same? Therefore, remove the data lock.

+4
source share
3 answers

Linter must deceive you. Because the right way to manage your context is with a context manager .

with LockGuard():
    # do stuff

Put information on how to get and release the lock in LockGuard.__enter__and, LockGuard.__exit__respectively.

__init__ __del__ , __del__ .

, ++ , , Python ? .

Python . , , . , (.. locker ), , , , , __del__ .

+10

__del__.

object.__del__:

: - , __del__(), [...]. :

  • __del__() , . __del__() - , , , __del__(). ( )
  • __del__() . [...]

- with .

+5

def f():
    a = 3

- : ;

from dis import dis

dis(f)

:

  6           0 LOAD_CONST               1 (3)
              3 STORE_FAST               0 (a)
              6 LOAD_CONST               0 (None)
              9 RETURN_VALUE

a (... - ). ; , .

, : .

+2
source

Source: https://habr.com/ru/post/1694615/


All Articles