May-24-2022, 04:57 AM
(May-23-2022, 08:49 PM)Clunk_Head Wrote: Can you please provide an example where an exception must be used in place of anything else?
Python documentation, glossary:
Quote:EAFP
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.
There are many countries out there with different notations. 1.000,42 and 1,000.42 are perfectly 'legal' and equal numbers, just depending your locale.
There is ast.literal_eval() which can be used (locale thingy still applies):
>>> import ast >>> ast.literal_eval('1.0') 1.0 >>> ast.literal_eval('+3') 3 >>> ast.literal_eval('-42') -42 >>> type(ast.literal_eval('-42')) <class 'int'>If you feed invalid value then you get SyntaxError:
>>> ast.literal_eval('1.0.0') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/ast.py", line 62, in literal_eval node_or_string = parse(node_or_string.lstrip(" \t"), mode='eval') File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/ast.py", line 50, in parse return compile(source, filename, mode, flags, File "<unknown>", line 1 1.0.0 ^^ SyntaxError: invalid syntaxYou can use EAFP style with try to literally evaluate value, catch syntax error if it's raised and do something about it
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.