09 April 2018

python string concatenation is a bad practice

i think because python is a scripting language, people tend to thing it's super fine to do something like this:

>>> val + '-string'

the problem is that the + operator does not do any casting of the variable to make it compatible with the string. this sort of thing will throw an error if the type of val is anything other than a string.

check it:

>>> val = None
>>> val + '-string'
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    val + '-string'
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
>>> '{}-string'.format(val)
'None-string'

>>> val = 4
>>> val + '-string'
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    val + '-string'
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> '{}-string'.format(val)
'4-string'

now, you could force cast it using str(val), but that seems silly when you can just use the format() method on the string object to handle things for you.

02 March 2018

python is referential

this is often misunderstood about python, especially if you are accustomed to other languages, such as C/C++.

>>> class thing(object):
...     def __init__(self, some):
...         self.some = some
...     def add_on(self, addition):
...         self.some = self.some + addition
... 
>>> a = thing("hello")
>>> print(a.some)
hello

>>> b = a
>>> print(b)
<__main__.thing object at 0x7f9d267cf7f0>
>>> print(a)
<__main__.thing object at 0x7f9d267cf7f0>
>>> print(b.some)
hello

>>> a.add_on(", world")
>>> print(a.some)
hello, world
>>> print(b.some)
hello, world

>>> print(a)
<__main__.thing object at 0x7f9d267cf7f0>
>>> print(b)
<__main__.thing object at 0x7f9d267cf7f0>