3

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)

ice-wind
  • 690
  • 4
  • 20
  • 1
    @CeliusStingher we don't know without more clarification from OP, but that thread is perhaps one part of the question. I assumed OP was asking broadly, i.e. are there any other issues returning like that could cause? (I'd say it's too broad as-is) – BruceWayne Oct 21 '20 at 18:15
  • 1
    @BruceWayne The duplicate thread answers the question, I just wanted to be sure ```return``` doesn't somehow break context managers, and it seems like it doesn't – ice-wind Oct 21 '20 at 18:25

1 Answers1

1

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

John Kugelman
  • 349,597
  • 67
  • 533
  • 578