Setting a parameter once and use it multiple times in python

  Kiến thức lập trình

I’m new to Python and I have a design question. I have a file in this structure:

@pytest.fixture( scope = "module", autouse = True )
def auth( input ) :
  body = {
           name= "secret"
           type="A"
         }
.
.
.

class TestArtifacts(object):
     def test_e2e( self, input):
     name = "secret"
.
.
.

    def test_e2e_2( self, input):
     name = "secret"
.
.
.
.

In my code, I’ve set the value of the variable name multiple times in more than one function. I want to read the name value from a JSON file once and use it here instead of a hardcoded value. My question is how I can read and set the parameter once and then re-use the value. Where is the best place to put this parameter?

EDIT: Can defining another @pytest.fixture to read the value of the name variable from a JSON file and return it, be a good approach in this scenario?

1

Your example shows two functions encapsulated in a class object. Why not use self-variables to store and use one input for both functions? It avoids the use of the globals keyword and can be easily accessed in your class functions.

class Foo:
    def __init__(self, input):
        self.input = input
    def bar(self):
        print(self.input) # prints your input argument from instance initialization

    def baz(self):
        print(self.input) # prints the same argument as bar

instance1 = Foo("test")
instance1.bar()
instance1.baz()

Output:

test
test


(dirty fix)
If you want to reuse any of your function’s parameter values (arguments), you could use the keyword global when defining variables.

The keyword global precedes the name of a variable whose value can be modified in a local scope (e.g., a function). It allows the local scope to access the value of your program’s global variables defined outside the local scope.

Example:

USERNAME = None

def copy_user(user):
    global USERNAME
    USERNAME = user

In the code snippet above, the function copy_user gains access to the global variable USERNAME and sets its value to the parameter user.

Generally, the globals keyword is bad practice as you tend to lose track of any global variables you’ve modified as opposed to local variables.

4

LEAVE A COMMENT