Is it handy to use the same variable for different things in a function

advertisements

In a function like the following:

def foo(case):
    if case == 1:
        my_var = []
        # then do something with my_var
    elif case == 2:
        my_var = {}
        # then do something with my_var

Since the variable my_var lives in different cases, so it shouldn't cause a problem at runtime. But is this a good practice in Python?


It may be confusing for other people who work on the same code. Several style guides also discourage reusing the same variable name for different purposes. If you can avoid it then you should, although there can also be good reasons to deviate from this rule. Are they really the same thing? One is a list of items, the other is a dictionary of values so what do they contain? If you can think of a more descriptive variable name then that's a good idea.