2

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Nathan Dai
  • 392
  • 2
  • 11

1 Answers1

0

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')
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • I don't think this question is the same as the one marked. I want to be able to import `a` or `b`. If I wrap the a inside an if name == main, then I won'd be able to import it. I want to be able to import a or b, and not compute one of them based on what is being imported. – Nathan Dai Sep 21 '21 at 15:43
  • @NathanDai Edited my answer – U13-Forward Sep 22 '21 at 01:14
  • Thanks for the update, but I knew that I could define functions and run them. I'm assuming there's no way to accomplish the same thing without importing the function. – Nathan Dai Sep 23 '21 at 02:03