skyork
skyork

Reputation: 7401

Is it good practice to use the same variable for different things inside a function

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?

Upvotes: 3

Views: 467

Answers (4)

K-man
K-man

Reputation: 364

I would say no, because then you have a greater chance of getting unexpected results and annoying debugging. But sometimes there could be a specific reason where this is a good idea. So it really depends on what you're doing.

Upvotes: 2

Sven Marnach
Sven Marnach

Reputation: 602305

Apply your own judgement. If you feel that the meaning of the object is similar in both cases, using the same name might improve readability. If you feel that using the same name for different things is confusing, don't do it.

Upvotes: 3

Silas Ray
Silas Ray

Reputation: 26160

Generally, no. When a variable means more than one thing, it adds potential confusion. Plus, if you ever have to refactor your code to add new features or something, you have a good chance of having made that task more difficult. That said, Python is a duck typed language, so if it is functionally the same thing but the data type is different, you are probably good to go.

Upvotes: 4

Simeon Visser
Simeon Visser

Reputation: 122476

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.

Upvotes: 9

Related Questions