Ashley Shen
Ashley Shen

Reputation: 115

Python Error "global name is not defined

My code:

def check_File_Type(self):        
    suffix={"docx","pptx","xlsx"}
    if [self.file_path.endswith(x) for x in suffix]:
        print(x)

what I wanna do is to return the file type if it is one of those in suffix. but I get the error "NameError: global name 'x' is not defined". seems like I can't use "x" since it's in the [statement]? then how can I print the x here?

thanks

Upvotes: 0

Views: 1414

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124518

x from the list comprehension is local to the comprehension; in Python 3, a list comprehension is executed in a new frame (like a function) and names in the expression are locals.

Use a generator expression with next() instead:

def check_File_Type(self):        
    suffix={"docx", "pptx", "xlsx"}
    x = next((x for x in suffix if self.file_path.endswith(x)), None)
    if x:
        print(x)

The next(iterable, default) form returns either the first element of the iterable, or the default. The generator expression returns any x that is a suffix of the file path.

An alternative approach would be to use os.path.splitext():

def check_File_Type(self):        
    extension = os.path.splitext(self.file_path)[-1].lstrip('.')
    if extension in {"docx", "pptx", "xlsx"}:
        print(extension)

Upvotes: 3

Related Questions