Python Forum
python manage variables across project level
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python manage variables across project level
#1
Hi Team,

how to manage variables which can be used in project level, instead of passing all variables from main def

In my project I am using total 10 modules. [no class module used]

in main function I have created all variables.
few functions are calling in same module, and passing 80% job to another module. main2 to finish.

from main_function I am passing all variables to main2 function which is in another module
and importing all functions from other module into main2 module.
and doing jobs.


import sys
import json

def main():    
    var1 =   sys.argv[1]
    var2  =   sys.argv[2]
    var3  =   sys.argv[3]
    var4  =   sys.argv[4]
    var5  =   sys.argv[5]

    with open("DBConfig.json","r") as myconfig:        
        obj = json.loads(myconfig)
        
        server = obj[1]
        database = obj[2]
        constant_path = obj[3]
        logging_path = obj[4]
        
        hd ,conn = connect_database(server,database)
        hd, conn = connect_SP(server, database,logger)
        
        #function call with
        main2(var1,var2,var3,var4,var5,var6,server,database,constant_path,conn,logging_path)
            pass
        
if "___name__ " == "__main__":
    main()
Reply
#2
This is ugly.
To start with, you should never have this many positional arguments in a function. I try to limit positional arguments to 1, maybe 2. I only use positional arguments if they make sense for the function, like list.append(item). For something like this I probably wouldn't have any positional arguments. Use named arguments instead.
meaningfully_named_function(
    your_name=sys.argv[1],   # Named arguments are self documenting
    your_quest=sys.argv[2],
    favorite_color=sys.argv[3],
    capitol_of_assyria=sys.argv[4],
    server=json_data["server"],
    database = json_data["database"],
    logging_path=json_data["logging_path")
5 positional command line arguments is a lot. Unless this is always called from a script or by another program it is going to be difficult for your user to get the order of the arguments right. You can use something like argparse to help with that. It can also help you keep the arguments straight inside your program.

The json file looks like it might be ugly too. This code makes it look like your json file should be a dictionary, not a list.
        server = obj[1]
        database = obj[2]  # key = "database"
        constant_path = obj[3]  # key = "constant_path"
        logging_path = obj[4]
Json files are not pretty, but they are human readable and editable. Instead of just containing a list of strings, your json file should have key:value pairs. The keys act like sign posts when reading the file. You don't have to remember the order of the fields because the fields all have names.

Here's an example I put together that uses argparse and reads a json file that contains a dictionary. This is the json file:
Output:
{ "name":"John Lithgow", "address":"Third rock from the sun" }
This is the program:
import argparse
import json

def do_math(operands, operator):
    """Something to receive operands and operator arguments"""
    if len(operands) < 2:
        print(operands[0], operator)
    else:
        print(operands[0], operator, operands[1])


def dump_json(filename):
    """Something to receive optional json file argument"""
    with open(filename, "r") as file:
        info = json.load(file)
    print(info["name"])
    print(info["address"])


# Configure the argument parser
parser = argparse.ArgumentParser()
parser.add_argument("operands", type=int, nargs="+", help="Operand(s).  1 or 2 depending on operator")
parser.add_argument("operator", type=str, help="Operator applied to operand(s)")
parser.add_argument("--json", type=str, required=False, help="json file with extra parameters")

# Parse the arguments.  Call the functions
args = parser.parse_args()
do_math(args.operands, args.operator)
if args.json:
    dump_json(args.json)
I can use -h or --help to ask the program for help with the command line arguments.
Output:
>>> python test.py -h usage: test.py [-h] [--json JSON] operands [operands ...] operator positional arguments: operands Operand(s). 1 or 2 depending on operator operator Operator applied to operand(s) optional arguments: -h, --help show this help message and exit --json JSON json file with extra parameters
Now that I know the arguments I can run it for real.:
Output:
>>> python test.py --json stuff.json 1 2 + 1 + 2 John Lithgow Third rock from the sun
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How do you manage script? kucingkembar 14 2,741 Oct-15-2022, 06:32 PM
Last Post: Gribouillis
  Python, how to manage multiple data in list or dictionary with calculations and FIFO Mikeardy 8 2,623 Dec-31-2021, 07:47 AM
Last Post: Mikeardy
  how to manage crypto trading flooding data from exchange servers Mikeardy 0 1,246 Dec-26-2021, 08:31 PM
Last Post: Mikeardy
  API Gateway to manage multiple API's get put data robsuttonjr 2 2,557 Mar-09-2021, 04:09 PM
Last Post: robsuttonjr
Photo Locate Noise floor level for a spectral data in Python Ranjan_Pal 1 3,066 Dec-19-2020, 10:04 AM
Last Post: Larz60+
  Manage user names in TRAC susja 3 6,013 Dec-06-2020, 09:34 PM
Last Post: susja
  How to manage multiple datasets in Python ThePhantom 2 1,936 May-06-2020, 12:17 AM
Last Post: ThePhantom
  how to manage an input() rodrigoH 1 1,647 Mar-16-2020, 12:24 AM
Last Post: jefsummers
  Questions re: my first python app (GUI, cross-platform, admin/root-level commands)? DonnyBahama 0 1,739 Feb-27-2020, 08:14 PM
Last Post: DonnyBahama
  Easier way to manage dependencies? Tylersuard 2 2,365 Jan-01-2020, 09:19 PM
Last Post: Tylersuard

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020