Import specific variables from file without computing others

Viewed 43

Let's say I run

from variables import b

and variables.py is as follows:

a = [i ** i for i in range(10000)] # or any other computation that takes a long time
b = 1

Is there a way to import b without computing a?

I was thinking that I could add an if statement like this:

if (variable_being_imported() == 'b'):
  b = 1
else:
  a = [i ** i for i in range(10000)]

I know I can define functions and run the functions after importing them, but is there a way without defining functions?

1 Answers

You could try in variables.py:

def main(var):
    if var == 'a':
        a = [i ** i for i in range(10000)] 
        return a
    else:
        b = 1
        return b

And import it this way:

import variables
b = variables.main('b')
Related