What is the difference between straight calling a function and assigning it to a variable?


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:


to have them built?

Thank you

Asked By: bmfy131



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):
    return Table()

x = fn()
print('last thing')


last thing

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 =:

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.

Answered By: Kelly Bundy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.