EAFP vs LBYL
I understand your dilemma, but Python is not PHP and the coding style known as Easier to apologize than for resolving (or EAFP ) the general coding style in Python .
See source (from documentation ):
EAFP - It's easier to ask forgiveness than permission. This general Python coding style assumes valid keys or attributes and throws exceptions if the assumption is false. This clean and fast style is characterized by many attempts and exceptions. This method contrasts with the LBYL standard common to many other languages, such as C.
So, basically, using try-catch statements here is not a last resort; this is a common practice .
Arrays in Python
PHP has associative and non-associative arrays, Python has lists, tuples, and dictionaries. Lists are similar to non-associative arrays of PHP, dictionaries are similar to associative arrays of PHP.
If you want to check if the "key" exists in the "array", you must first indicate what type it is in Python, because they throw different errors when the "key" is missing:
>>> l = [1,2,3] >>> l[4] Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> l[4] IndexError: list index out of range >>> d = {0: '1', 1: '2', 2: '3'} >>> d[4] Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> d[4] KeyError: 4
And if you use the EAFP coding style, you should just catch these errors appropriately.
LBYL Coding Style - Checking for Indexes
If you insist on using the LBYL approach, these are the solutions for you:
for lists, just check the length, and if possible_index < len(your_list) , then your_list[possible_index] exists, otherwise it is not:
>>> your_list = [0, 1, 2, 3] >>> 1 < len(your_list)
for dictionaries, you can use the in keyword, and if possible_index in your_dict , then your_dict[possible_index] exists, otherwise it is not:
>>> your_dict = {0: 0, 1: 1, 2: 2, 3: 3} >>> 1 in your_dict
Did it help?
Tadeck Dec 20 2018-11-12T00: 00Z
source share