Rapid
Rapid

Reputation: 1502

Need help properly using variables, python

So I have a lot of functions in a file called definitions.py

My main file main.py which accesses those definitions and also has functions of its own using those functions.

Now in main.py I have 'from definitions import *'

Both files rely on a set of 15 initial variables, these variables I have placed in definitions.py, this is all well and good I have all my functions working fine, the problem arises when I want to use my application as a model, where I will want to change some of the variables to see how the output differs.

Essentially I want my initial variables to be in a sort of bowl which is accessed each time a function is called and I can swap and change the values in this bowl which means the next function that is called uses the updated variables.

The problem I'm having at the moment is, I think, because the variables are written in definitions.py that's that and I can't change them.

Even in python shell I can put n1 equal to something else, execute a function that uses n1 but it will use the old n1, not the new one, I think because the variables haven't changed in the definition.py file.

Is there some sort of way to have live access variables that I don't know about? Thank you.

Upvotes: 1

Views: 108

Answers (1)

HerrKaputt
HerrKaputt

Reputation: 2604

You should use a class. For example, if your definitions.py file has:

variable1 = 3
variable2 = 'stuff'

def spam(arg1):
    return 'spam' + arg1

def eggs(arg1,arg2):
    return 'eggs' + arg1 + arg2

change it to

class Definitions():
    def __init__():
        self.variable1 = 3
        self.variable2 = 'stuff'

    def spam(self,arg1):
        return 'spam' + arg1

    def eggs(self,arg1,arg2):
        return 'eggs' + arg1 + arg2

Now, from your main.py file, you can import in a slightly different way and sweep multiple parameter values:

import definitions

for parameter in xrange(0,10):
    defs = definitions.Definitions()
    defs.variable1 = parameter

    # do some stuff and store the result

# compare the various results

Remember that now your functions are inside a class, so instead of calling spam('mail'), you should call defs.spam('mail'), and so on.

Upvotes: 3

Related Questions