For simple control statements,
x = 1
if x > 0:
print('true')
else:
print('false')
We all know that when x > 0 is determined, the else statement will not be executed.
# filename test.py
def test1():
pass
# test1()
The following is my understanding that I don’t know whether it is correct or not:
1, for java, if the line of code test1() does not execute the call to function test1, then the entire program is basically meaningless, there will be no memory allocation, and there will be no execution
2. But for python, the test1 function object will be created, and then a series of operations in test1 will be saved. These operations will not be executed. Even if the entire program does not make any calls to test1, as long as the program does not end, then test1 will always exist in memory.
The reason is that after the program is run, the function test1 will become the attribute of the current module object, that is, module __main__
.
3. As for the function name 'test1', it refers to this function object, so even if the function is not called, the garbage collection mechanism will not recycle it
# filename test.py
def test1():
def test2():
pass
# return test2()
# test1()
>>> class A(object):
a = []
def test1(self):
pass
@classmethod
def test2(cls):
print('cls.a', sys.getrefcount(cls.a))
print('cls.test1:', sys.getrefcount(cls.test1))
>>> A.test2()
('cls.a', 2)
('cls.test1:', 1)
>>> def test3():
def test4():
pass
>>> sys.getrefcount(test3)
2
>>> dir(test3)
['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']
# sys.getrefcount(test4) NameError: name 'test4' is not defined
def test3():
def test4():
pass
return test4 # return test4()
It is recommended to split this question into two different questions in the future.
(1) This function is not called. Python has another memory management strategy, reference counting: "Principle: Record the number of times an object is referenced by other objects. When the reference to this object is removed, the reference count is also reduced. If it is reduced to 0, the object will be released." So I guess, it should have been recycled during reference counting.
(2) Whether it is called depends on whether the reference of an object has been removed and whether there is a reference cycle. There is a similar discussion in the email discussion thread here. I don’t know if it answers your question.