2

[Couldn't find exactly what I wanted. Apologies if this is a duplicate question.]

In this code:

import heavy_function

_data = heavy_function()

def foo():
    print _data

def bar():
    print 'Call no 1'
    foo()
    print 'Call no 2'
    foo()

bar()

If I am calling

bar()

as it is shown in the code, or if I call it from other module by importing it, does the

_data

get loaded each time the function calls it? or does it get loaded once and be stored for further use?

3
  • Once the statement _data = heavy_function() is executed the return value is stored in the variable and hence every time you use the variable the stored value is displayed Commented Aug 28, 2015 at 18:45
  • _data is a name that points to the return value of the function, you assign it once so the function is called once Commented Aug 28, 2015 at 18:49
  • Thank you people. That is what I intuitively expected, wanted to be sure. Commented Aug 28, 2015 at 19:02

3 Answers 3

2

As soon as you load this module your heavy_function() gets loaded and store it's value into _data and this _data gets stored in globals(). And then it doesn't matter how many time you use that same object gets passed over.

For your understanding here I'm simultaing the function value just by giving a list [1, 2, 3], here I'm checking the object identity by comparing foo() return value with _data and refcount to show that it not getting referenced more than once.

#import heavy_function
import sys
_data = [1, 2, 3] # heavy_function()

def foo():
    print _data

def bar():
    print 'Call no 1'
    value1 = foo()
    print sys.getrefcount(_data)
    print 'Call no 2'
    value2 = foo()
    print sys.getrefcount(_data)
    print 'call no 3'
    value3 = foo()
    print sys.getrefcount(_data)

    print 'Check referenced values..'
    print value1 is value2 

bar()

Output:

Call no 1
[1, 2, 3]
2
Call no 2
[1, 2, 3]
2
call no 3
[1, 2, 3]
2
Check referenced values..
True

Here if you see even after the third call the same object is getting returned from foo and this print value1 is value2 one helps you to identify that.

Sign up to request clarification or add additional context in comments.

2 Comments

My best gratitudes to you, @gsb-eng. I didn't know the getrefcount() function. This is cool!
I didn't know how mark as accepted. I thought I don't have enough reputation to do anything :) You answer IS the best!
0

It's loaded once, then the returned value is referenced twice

Comments

0

_data will be assigned the return value of heavy_function() only once (when the module is first imported or run). After that it will simply be accessed.

You should be careful not to try to assign it inside a function though without specifying first that it is a global by using the global keyword.

1 Comment

Suggesting global is a bad idea.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.