python: SyntaxError: invalid syntax Expected member name after "."

Viewed 344

I'm using argparse to parse the parameters, but when I get args.global, a strange error appears, I don't know where I did it wrong


...

parser.add_argument('-u','--update', action='store_true', default=None)
parser.add_argument('-g','--global', action='store_true', default=None)
args = parser.parse_args()

...

if args.update:
    print(args)
    print( args.global )
    print( args.update )
$ python ./anpm.py -g -u
  File "./anpm.py", line 67
    print( args.global )
                     ^
SyntaxError: invalid syntax

This is the error given by vscode

enter image description here

$ python --version
Python 3.6.8
3 Answers

global is a keyword in Python (as are if, while, etc.) and you cannot use these as attribute names, which means they also don't work in a NameSpace object.

More on that here: https://docs.python.org/3/reference/lexical_analysis.html#keywords

However, you can still access these values if you need to use these names:

my_args = vars(args)
print(my_args['global'])

This works because it doesn't use the reserved word, instead it just uses a string (containing the reserved word) to access its value.

If you only need access once, or infrequently and you don't want to keep the vars() result around, you can also just:

print(vars(args)['global'])

Use getattr:

print(getattr(args, 'global'))

This would get the attribute global.

Global Explanation

Global is a reserved keyword in python that is used to declare a variable globally inside the functional scope. Example:

def p():
    global x
    x=23
p()
print(x)
//returns 23

Keywords and example

A keyword can't be used as an argument or a variable in python. you can have other examples like

yield=23
return=34
pass=34
continue=23
.....

All these make an error.

Solution

Try changing the name from global to __global or _global or something like this.

Related