-1

I have the following code inside a try/except block:

if current_path is not None and isinstance(current_path, str) and os.path.exists(current_path):
                os.chdir(current_path)

Under normal circumstances this works fine, however if the code fails before current_path gets assigned I get an error saying it's referenced before assignment. The first condition in the if statement is to check that it gets assigned or not, I was under the assumption that if the first condition is false, i will always get false is this not the case?

Any suggestions as to how to do this better? My only other thought would be a nested if statement. Any suggestions would be appreciated.

Ted
  • 365
  • 1
  • 7
  • 16
  • Possible duplicate of [Does Python support short-circuiting?](https://stackoverflow.com/questions/2580136/does-python-support-short-circuiting) – Scott Hunter Oct 23 '19 at 19:51
  • "if the code fails before current_path gets assigned I get an error saying it's referenced before assignment": we don't see no assigment to current_path here. – Jean-François Fabre Oct 23 '19 at 19:53
  • note that `current_path is not None` is not needed as `isinstance(current_path, str)` would filter out `None`. Also, unassigned/undefined variables aren't None. They just don't exist – Jean-François Fabre Oct 23 '19 at 19:54

2 Answers2

1
if current_path is not None:

That condition alone is not enough to check if current_path has been assigned yet or not, only if it is None or not (it isn't None before it's assigned / defined - it just doesn't exist).

A correct way to check if it exist at all would be the python way of "asking forgiveness, not permission" with a try...except:

try:
    if current_path is not None:
        do_something() # current_path is both assigned and is not None
    else:
        something_else() # current_path is assigned but is None
except NameError:
    handle_it() # current_path has never been assigned / defined
Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62
0

This is unrelated to and. You say you want your code to act as if current_path is None before it's assigned somewhere in your try/except block. In Python, you need to do that explicitly:

current_path = None

somewhere earlier in your code so that you can be certain it's run before your if statement.

Dan Getz
  • 8,774
  • 6
  • 30
  • 64