Home > Software design >  How to use a var in multiple methods in python
How to use a var in multiple methods in python

Time:10-29

I have a few files in my code that speak to the database

This might look something like this:

def addUser():
  # some code

def verifyUser():
  # some code

def addStuffToDB():
  # some code

In all of the above I need to use a variable - let's call it db - that holds a reference to the database (as opposed to redefining it in every function)

How would I do this? How can I have functions in one or more files that all make use of a variable (in this case db)

Thanks

CodePudding user response:

If you have all this functions inside the same file, it is enough to just define variable db outside any function (this will make it global). Now all functions will be able to see db variable. But if you change db inside a function it will not change outside the function.

If you have this variable in another file you can simple import it like

from file_name import db

CodePudding user response:

As @ddejohn said, you should wrap your functions in a class, so the variable self.db would have a class scope.

class DB():
    def __init__(self) -> None:
        self.db = "DB_connection or something..."


     def addUser(self):
        #Some code, acess db variable with self.db

    def verifyUser(self):
        #Some code, acess db variable with self.db

    def addStuffToDB(self):
        #Some code, acess db variable with self.db

MyDB = DB()

MyDB.addUser()

CodePudding user response:

Thanks for asking the question. You need to pass db as argument while calling the funcs like the following

db = "some referenec"
def addUser(database):
    ## now you can use db
  # some code

def verifyUser(database):
  # some code
  ## now you can use db

def addStuffToDB(database):
  # some code
## now you can use db
## while calling each func pass db as argument like this
addUser(db)
verifyUser(db)
addStuffToDB(db)

CodePudding user response:

add a db paramenter to yout funcs:

controller.py:

def addUser(db):   # some code
    obj.add(db)

def verifyUser(db):   # some code
    obj.verify(db)

def addStuffToDB(db):   # some code
    obj.add_stuff(db)

Then, you can use as follows:

view.py

import db
from controller import addUser

    
addUser(db)
  • Related