2

When you have a variable (say, a dict) which is set by a method, what is Python's best practices recommendations:

Should I initialise my_var first:

my_var = {}
my_var = do_something_and_return_var()

or set it straight away:

my_var = do_something_and_return_var()

The advantage of setting it first is that you can tell staight away what type my_var should be (and although I don't use an IDE, I guess it could help when you do). But on the other hand it my seem a bit useless to set it to an emtpy dict right before you set it to it's actual value.

Thanks

1
  • 2
    do my_var = do_something_and_return_var(), you could always add a type hint Commented Jul 31, 2018 at 9:29

2 Answers 2

3

You don't need to write my_var = {} first. If you want to designate the type you should use type hints.

from typing import Dict

def do_something_and_return_var() -> Dict[str, str]
    ...
Sign up to request clarification or add additional context in comments.

1 Comment

Didn't know about the type hints, I'll have a look at that. Cheers
3

There is no advantage for setting the value to empty dictionary because when you do:

my_var = {}

a name my_var is simply bound to object empty dictionary stored in some memory location . so if your function do_something_and_return_var returns let's say an integer value , the name my_var will then be bound to this int value object while your empty dictionary object still stored in some memory location with no name bound to it which gets later removed by Garbage collector

1 Comment

Ah yes, of course. I hadn't thought about that, but it totally makes sense. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.