I know Python is a dynamic language and declaring variables before-hand is generally not necessary, but in the case where I need to create a variable and then give it a value later, both of the following methods work:
some_variable = ''
some_variable = str()
Is there a difference between both of these and which is considered best practice?
Example:
some_variable = str()
for number in range(10):
some_variable += str(number)
print(some_variable)
Works for both some_variable = '' and some_variable = str()
By best practice I do not mean "which is best coding style/most readable" but rather factors such as memory consumption, speed and which on the whole is more reliable for general use.
If you want to initialize a variable to an empty value, using an empty value literal will be slightly faster, since it avoids having to do a name lookup.
That is, if you write:
some_variable = str()
Python first needs to make sure you haven't written something silly like
str = int
in some visible scope first, so it has to do a recursive name lookup.
But if you write:
some_variable = ''
Then there's no way that '' will ever be anything but a str. (Similar principles apply for list and tuple literals: prefer [] and () over list() and tuple().)
More generally, though: initializing a variable to an empty value is generally considered a code smell in Python. For things like an empty list, consider using a generator expression (... for ... in ...) or a generator function (using yield) instead -- in most cases you can avoid setting up empty values at all, and that's generally considered a more Pythonic style.
I know Python is a dynamic language and declaring variables before-hand is generally not necessary
What? First of all how is declaring a variable before hand related to being dynamic or not? Secondly how can you even imagine any language that forbits declaring a variable "before-hand" (whatever that means) to work? You need to declare some variable directly at some point.
Is there a difference between both of these and which is considered best practice?
Yes, there are differences. Consider this:
def str():
return 1
x = str()
Python does not protect you from variable shadowing. But the literal empty string '' cannot be shadowed. That's a difference on the functional level.
There is also a difference on the performance level: x = '' is slightly faster then x = str() due to being translated to a different bytecode. After all x = '' does not require a function call (which cannot be optimized again due to variable shadowing).
And finally esthethics: x = '' is probably more readable then x = str(). Again since you need to be sure what str() actually is in the context.
So all in all: go with x = ''.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With