Sunday 20 March 2022

Python Strictness

I really like JavaScript and Python a lot, both being so profoundly dynamic, and very similar in many aspects, but there are some points where Python is a bit "strict" when compared to JavaScript, and you have to be more careful, let me explain.

Access to non existing items
In JavaScript, access to an index beyond the array length, or to a non existing key in an object or a map, just returns undefined


> let ar = [];
undefined
> ar[2];
undefined

> let ob = {name: "Francois"}
undefined
> ob.city;
undefined


> let m = new Map();
undefined
> m.set("a", "aa");

> m.get("b");
undefined


In python we have to be much more careful, as that kind of access will throw exceptions. So we'll have to check for the array length, the existence of a field via the hasattr() function, and the existence of a dictionary key via "if key in dict" (the has_key() function is deprecated)


>>> ar = []
>>> ar[1]
Traceback (most recent call last):
  File "", line 1, in 
IndexError: list index out of range

>>> d1 = {"name": "Francois"}
>>> d1["city"]
Traceback (most recent call last):
  File "", line 1, in 
KeyError: 'city'

>>> if "city" in d1:
...     print("key exists")
... else:
...     print("key does not exist")
key does not exist

>>> class Person:
...     pass
... 
>>> p1 = Person()
>>> p1.name
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'Person' object has no attribute 'name'

>>> hasattr(p1,"name")
False
>>> 


Function parameters/arguments

In JavaScript you can invoke a function with whatever arguments you want, regardless of the parameters defined in the function signature (obviously, the function code will work or not depending on how those arguments are used)


> function fn(a, b){}
undefined
> fn();
undefined
> fn(1,2,3);
undefined


In python you have call the function with a number of arguments that matches the parameters defined in the function (save if you've defined them as *args, **kwargs)


>>> def fn(a,b):
...     pass
... 
>>> fn()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: fn() missing 2 required positional arguments: 'a' and 'b'
>>> fn(1,2,3)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: fn() takes 2 positional arguments but 3 were given
>>> 


strings and null/None
In JavaScript you can print (console.log) a null or undefined value, same as in Python you can print None. But in Python you have to be careful when using "+" for string concatenation (but well, most likely you're using f-strings, right?)


>>> a = "Hi"
>>> b = None

>>> st = a + b
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate str (not "NoneType") to str


>>> st = f"{a} - {b}"
>>> st
'Hi - None'

No comments:

Post a Comment