I know this is a super basic question, but I need to know if I understand.
If I have this function:
def fn():
# connections to a db and builts tables and runs things externally
return "all the tables that were built"
if I write:
x = fn()
do all those external operations still happen? like the tables being built and all that?
or do I run this:
fn()
to have them built?
Thank you
The x = fn()
might do less. Imagine one of your returned tables only commits its actions when it gets deleted:
def fn():
class Table:
def __del__(self):
print('commit')
return Table()
x = fn()
print('last thing')
Output:
last thing
commit
Since we hold on to the table, it won't get deleted right away and its actions won't be committed right away. Only at the very end of the program does that happen then, when Python shuts down and deletes everything. Or maybe not even then, see Silvio's comment and the doc ("It is not guaranteed that __del__()
methods are called for objects that still exist when the interpreter exits"), or if Python or your computer crashes.
Output if I remove the x =
:
commit
last thing
Now we don't hold on to the table, so nothing references it anymore and it gets deleted right away and the commit happens right away.