![]() ![]() Python is usually clever and won't generally return NaN from math functions, e.g. Also be careful with any other arithmetic operation when working with code that might produce NaN, as it will propagate through all operations without raising an exception. So, in case you need to test for NaN or inf, then you should use math.isnan() and math.isinf(). NaN in Python will never compare as equal even when compared with itself. The above code shows the non-reflexivity of NaN. Z = float("inf") # Define more "Infinity" X = float("NaN") # Define "Not a Number" (the string is case-insensitive), equivalent of math.nan So, let's demonstrate this by making a few comparisons with these values: Working with floats and non-integer numbers can often be difficult and annoying, but it gets especially weird when you get into Not-a-Number and Infinity territory. ![]() To avoid this issue, make sure you never reuse values when using setdefault. That's because default value passed to setdefault is assigned directly into the dictionary when the key is missing instead of being copied from original. In the below code we can see some surprising results:Įven though we didn't touch the data dictionary above, it was modified by appending to default value val. Similar behavior to the default arguments above, can also be seen with tdefault(key, value). To avoid this problem, you should always use None or other immutable type instead, and perform check against the argument as shown above.Įven though this might seem like nuisance and a problem, it's an intended behavior and it can also be exploited to make caching functions which can use the persistent mutable default argument as cache: Instead, the recently used value will be passed in, which in case of mutable types is a problem. The problem with using mutable value as default argument is that the default argument in not initialized every time the function is called. Setting default argument to a mutable value such as list or dict can, however, cause unexpected behavior: Setting default arguments for a function is very common and useful for defining optional arguments or arguments that can usually use same, predefined value. So, to avoid unnecessary rage and frustration over some weird issue in your favourite programming language, here follows a list of common Python pitfalls, that you should try to avoid at all costs. Python aims at being clean and simple language, yet it also has its portion of gotchas and quirks that can surprise both beginner and experienced software developers. Regardless of which programming language you're coding in, you've probably encountered good chunk of weird and seemingly unexplainable issues that ended up being really stupid mistakes or quirks of that specific language. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |