Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is returning inside a 'with' statement dangerous? [duplicate]

I need to return the contents of a file, is it fine to do this :

def foo(filePath):
    with open(filePath) as f:
        return json.load(f)

Or should I do this instead :

def foo(filePath):
    with open(filePath) as f:
        r = json.load(f)
    return r

(Of course my functions do other stuff, this is a toy model)

like image 320
Crysambrosia Avatar asked May 20 '26 03:05

Crysambrosia


1 Answers

Returning inside a with block is not dangerous. Write it the first way.

like image 141
John Kugelman Avatar answered May 22 '26 17:05

John Kugelman