Home > other >  how do I change the Item behind args. in the function?
how do I change the Item behind args. in the function?

Time:07-22

import argparse


def None_Check(args, arg): #my IDE shows me that arg is not used
    
    if args.arg == None: 
        return False
    return True

parser = argparse.ArgumentParser(add_help=True)
#adding some arguments to parser
args = parser.parse_args()

print(None_Check(args, "URL"))

What do I have to do to change args.arg to args.(the string I provide with arg) so the parameter arg is actually used behind "args." in def None_Check?

CodePudding user response:

I guess there is a logic error as arg is a variable under a function name none_check. It will run a attribute error as there is no namespace doesn't have attribute arg.

def None_Check(args,arg): 
if args.arg == None:
    return False
else:
    return True

in this args.arg is creating an error as the method of passing variables inside a function is not defined under any manual.

CodePudding user response:

As you can see in "What is the right way to treat Python argparse.Namespace() as a dictionary?" there are mainly two ways of doing this:

With vars():

import argparse
    
    
def None_Check(args, arg):
    if args[arg] == None:  # Get the dict value for the key in arg
        return False
    return True

parser = argparse.ArgumentParser(add_help=True)
#adding some arguments to parser
args = parser.parse_args()
args = vars(args)  # Converts the args Namespace to a dictionary

print(None_Check(args, "URL"))

With getattr():

import argparse


def None_Check(args, arg):
    if getattr(args, arg) == None:  # Get the attribute wich name is the string in arg
        return False
    return True

parser = argparse.ArgumentParser(add_help=True)
#adding some arguments to parser
args = parser.parse_args()

print(None_Check(args, "URL"))
  • Related