145 points · by knowsuchagency · 9y ago · 146 comments
Personally I think types are over-hyped for most (profane) code.
The problem with complicated and/or specific types (which promise to catch more errors) is, in one word, coupling. They create serious dependencies across the whole project or even across project boundaries.
The other problem is: one functions-guy's URL is the next function-girl's string. And all this up- and downcasting usually creates considerable noise. Often overzealous typing is painting oneself in a corner, creating more pain then relief. It's like creating these totally arbitrary object-oriented inheritance-based taxonomies which might make some sense in one place of the code but totally break down in the next place.
But speaking about primitive types like int and str, or maybe list of int - most function arguments can accept only one of those for the code to make sense. So strategically placed type annotations can help reduce some boilerplate and put some useful barriers for error search there. While the simple-types cases are also the easy ones - the first thing you'll notice while testing is usually that you put a str where an int was expected.
With dynamic typing, you'll still have this coupling, but now it's unchecked and (in practice) undocumented.
For example, in Haskell there is the filter function:
filter :: (a -> Bool) -> [a] -> [a]
filter _ [] = []
filter pred (x:xs)
| pred x = x : filter pred xs
| otherwise = filter pred xs
It doesn't actually care what (the type of) a is. This is one of the showcase examples of the power of Haskell's typesystem. (And admittedly it works nicely in this case).But you can have that easily with no typing at all.
def filter(pred, xs):
return [x for x in xs if pred(x)]
So, dependencies avoided and it's not a huge source of bugs. While in the typed case, a system is needed to prove that the properties that get input come out again (or possibly a function of these properties). That quickly gets quite involved for more advanced cases.Just look what the average Haskell code looks like, how many language extensions are typically needed, how crippled the code typically is (libraries dictating exactly what properties the client must be able to statically precompute). Most of the Haskell community seems to agree that the end-goal would be a practical system for dependent types (the unification of types and values, i.e. no types at all ;->).
For example, there are some libraries trying to capture the construction and execution of valid SQL queries in the type system. To understand these libraries without doubt a genius-level IQ is required. But the client code is still basically an unreadable mess. And the libraries are not reusable for cases where the database schema isn't known at compile time. The static type system actually prevents code reuse -- it makes the code really inflexible.
Like I said, the coupling is still there, but it's hidden by dynamic typing.
from typing import Callable, Iterable
def filter(pred: Callable, xs: Iterable) -> Iterable:
return [x for x in xs if pred(x)]
filter(lambda x: x>1, [1,2,3])
If you tighten it up to only take iterables of ints. from typing import Callable, Iterable
def filter(pred: Callable, xs: Iterable[int]) -> Iterable:
return [x for x in xs if pred(x)]
filter(lambda x: x>1, [1,2,3])
filter(lambda x: x>1, [[1],[2],[3]]) # this is an error
Float is duck type compatible with int. So if you specify float, it accepts ints and floats. If you specify int, it only accepts ints. from typing import Callable, Iterable
def filter(pred: Callable, xs: Iterable[float]) -> Iterable:
return [x for x in xs if pred(x)]
filter(lambda x: x>1, [1,2,3])
filter(lambda x: x>1, [1.01, 2.09, 3.34])
The moral of the story is to be as accepting as you can be unless there is an actual need to be very picky about what you accept. (Perhaps if you're doing integer arithmetic, and your code only works with ints, then require ints).For example if you define a TypeScript interface
interface Serializable {
toJSON():string
}
then any object that has a toJSON() method that returns a string is automatically accepted as a Serializable. You can even define such anonymous interfaces inline without giving them a name: function frob(obj:{toJSON():string}) {
// do stuff
}
Basically, you get statically checked duck types and no coupling.Basically the only way to really eliminate coupling that I see, is passing explicit function dictionaries, and retract the idea that there is only one valid implementation of any given (type, concept) tuple.
It's very bad if all interface implementations have to be physically coupled with the implementation of the class itself (as I think the case is with Java).
It's still at least unflexible sometimes if you are free to put the implementation anywhere (at the class definition site, at the interface definition site, at an independent site) but the system enforces that there is at most one implementation of each interface (this is how it's done in Haskell). This strongly discourages alternative implementations because on has to circumvent the machinery. I don't think there can be a system that automates away at least part of the boilerplate that is dictionary passing, while still retaining the flexibility to choose alternative implementations.
The Haskell (maybe also TypeScript?) way can be very nice if you can be sure that there can be only one valid implementation of a concept. However, most concepts actually don't lend themselves to a single implementation. Most concepts aren't mathematically pure enough for there to be one and only one canonical implementation. Right now I can think only of a few where it's almost always fine to use the default implementation instead of being explicit, because one doesn't care much about the result - like "Show" for debug output.
Take for example JSON: I can think of a thousand ways to create some JSON output from my global data. To get them all in the bag, you would start introducing phantom types and what not, and implement toJSON on those. Really nothing gained at this point, it's only losing some readability at the use site.
Given some run-time introspection or metaprogramming on the other hand, a lot of flexibility can be won back.
Here is an example of my preferred way to do it (metaproramming)
https://github.com/jstimpfle/python-wsl/blob/master/wsl/pars...
Just spend 5 lines to get the data in shape for the task at hand. The original function dict, having a specific layout convention, and containing functionality that is just not needed here, is specified here (informally)
https://github.com/jstimpfle/python-wsl/blob/master/wsl/doma...
So 5 lines and these two locations are completely decoupled. Easy.
Example: https://goo.gl/LphqrJ
Its possible to map over record fields of different types to transform the inner type of a field. Similarly, if I understood it correctly, for your example that would mean you could map an object where every field is of a different but related type Domain<T[Key]> into an object of the same shape containing WsllexFunc<T[Key]> or Decoder<T[Key]>.
Furthermore, you don't have to use Domain<T[Key]> - you can define a more restricted interface that only requires wsllex and decode. Then the extra functionality defined in the Domain<T[Key]> is no longer required, nor mentioned. Similarly the types WsllexFunc<X> and Decoder<X> are simple function types, and any function types with the same shape (arguments and return type) would be accepted regardless of their name. Recursively the arguments and return type are themselves structural, and so on (!)
IMO its incredible how structural type systems change the game completely and we've yet to realise the full implications of this for dynamic languages. My guess is that this is why Guido is excited about types.
Btw. going through your older posts
> Besides immutability, what are the advantages of using namedtuples instead of dicts?
fixed attributes. And they are ordered! :-)
Makes sets / db-style programming so much simpler:
for user, name, account in users:
...
You can do that with conventional tuples as well, but they can't match the introspectability and the value for documentation.We're big fans of type aliases also. For example, API functions do not return an int, they return a PK. They do not return a str (or Text), they return a URL.
We're also heavy users of typing.Optional to mark parameters or return values that can accept and return None.
We tried mypy but it failed miserably on our large codebase and frankly, with our large test suite, we never had a typing error found in production so I think it's not a good investment of our time.
I'm eager to test type annotations with our next intern to see if it speed up the ramp up process.
I've just finished porting a small application to Python 3 just because 2020 and deprecation is in sight already - there are so many things that have passed me by in the Py3 world.
Asyncio was provisional until Python 3.6, so it is effectively a Py 3.6 feature that has been backported to 3.5 in time and space.
Python (currently) doesn't actually check actual types are per their annotations. Do you mean that you rely on, say, your IDE to do static analysis to ensure everything's lined up, or that just by virtue of having annotations, your team can reason about things more easily?
That's one thing I don't really like about type annotations in Py3.5+, unless you run it through a static analyser or have an IDE that understands them, they're effectively just noise. As such, I have mypy running through Syntastic, in Vim, and while not perfect it's a vast improvement over non-annotated Python.
We use types as a documentation tool so the noise you are talking about is actually very useful to us. When someone unfamiliar with the code wants to call a function, a quick look at the signature is usually enough now that we use type annotations. Before that, we provided that information in a docstring, which was more verbose so longer to write and longer to read.
We found PyCharm to offer a better out of the box validation experience than mypy (less configuration), but it's not perfect, i.e., we still see occasional false negatives and false positives. Ultimately, we did not include type checking in our build pipeline, but as the tooling becomes more mature, we will definitively revisit that decision.
[1] I know other languages have more powerful type systems that may have prevented some errors we encountered, but I don't have enough experience with these type systems applied to large systems to comment on that.
That's because your devs had already suffered this bug in their test runs once too many times, and killed it before it got to production.
That, and luck.
Enumerations are useful for a number of reasons in typed, compiled languages (I guess they provide readability in Python), but they are not the same as monads (of which Either is one type). I am not a Python developer, but as far as I can tell, this implementation gets you none of the real benefits that an a true Either implementation would get you in terms of functional goodness.
Am I missing something here? Is there some kind of Python magic that makes this better than just propagating the exception?
Well, if we want to take the title literally:
Error handling is a fundamentally Modernist idea - shoring up errors and "correcting" or at least containing them.
Postmodern error handling would be anything that reasonably counts as a reaction against Modernist error handling. The most basic would be not handling errors at all, and instead embracing the chaos of an error-prone system, and designing a system in which errors propagate but converge to a desirable value.
I found that enlightening, but it is probably also splitting hairs with regards to the blog post.
You're thinking of Modernism. Postmodernism is more like 60 years old, depending on how you draw the line, and it's still an ongoing and developing set of philosophies.
But within your own code, you would not want to represent "an unforeseen error occurred" with a value, no matter how much you like enums.
If you were parsing JSON and you got an unexpected error that isn't about parsing JSON, logging the error and continuing is not the right option. There is probably nothing reasonable your program can do. Raise the error so your broken code stops running.
For instance when making an HTTP request. The requests library can throw thousands of different errors (SSLError, BrokenPipe, socket errors, errors from urllib, errors from requests itself...).
As far as I know, it is the only choice if you want to know if a request succeeded or not so you can deal with it without your view returning a 500.
I would really appreciate if someone has another solution to this.
(Well, there's one thing wrong, which is that certain standard library errors in Python 2.x don't derive from Exception [socket error, I'm looking at you]. This has been addressed in more recent pythons, but there's still lots of 2.x out there.)
Python's rules for handling exceptions in a class hierarchy are designed to provide programmers with the ability to handle errors at whatever level of granularity makes sense. If your requirements say that the software should treat SSLError and BrokenPipe differently, then by all means, handle them separately.
More often, however, you're making a library call for which any failure has identical requirements. When you're trying to read a configuration file, you probably don't care whether a hard drive is corrupted, has a loose power cable, is on fire, or somehow triggered a divide by zero error somewhere in the bowels of an I/O library.
>>> import socket
>>> issubclass(socket.error, Exception)
True
It's been like this since Python 2.4 at least.[0]: http://docs.python-requests.org/en/master/_modules/requests/...
For python urllib IOError and OSError should suffice. At least in py3.
import urllib.request
try:
urllib.request.urlopen('https://wrong.host.badssl.com/')
except (IOError, OSError):
pass
causes: ssl.CertificateError: hostname 'wrong.host.badssl.com' doesn't match either of '*.badssl.com', 'badssl.com'But for how to do with errors, see the sibling comments to this one, and good libraries will give you an inheritance tree of exceptions
By catching all exceptions as close as possible of the request you make, you can at least do something about it.
As for the tree of exceptions, it works well for a while until networks become unreliable, until remote peers start presenting certificates broken in subtle ways... You end up adding ranges of exception in the except clause as new ones are popping on Sentry. Then you get tired of it so you catch "Exception".
This is the unfortunate story of every single project I do that deals with network calls on the Internet.
My modules do catch SystemExit and KeyboardInterrupt before the bare exception and simply re-raise those.
Another strategy is to catch the "expected" exceptions first followed by a general exception handler. This can use the `traceback` module to log the call chain and error message.
try:
[...]
except Exception as e:
log(e)
It's not much longer than `except Exception: pass` and you gain more control over your system.Any error that does not inherit from our top-level exception is a bug: please let us know so we can fix it.
except (aiohttp.ClientError, aiohttp.DisconnectedError, aiohttp.HttpProcessingError, aiodns.error.DNSError, asyncio.TimeoutError, RuntimeError) as e:
I want to continue running no matter what, so I also have an "except Exception", but I have better logging now that I know what the known vs. unknown exceptions are.
try:
do_something()
except ExpectedException:
handle_it()
except OtherKnownException:
handle_that_too()
except Exception as exc:
log.exception('New kind of error just happened')
handle_fallback()This (pokemon exception handling) is a massively, massively destructive anti-pattern.
Once a code base grows beyond a certain size it usually leads to failures which manifest themselves with strange behavior that takes hours (sometimes days) to track down the real source of.
try:
...
except (NameError, AttributeError, TypeError):
# likely programming error
raise
except Exception:
...
Not pretty, but maybe better than catching every exception.I actually use this pattern quite frequently in one very specific place. I use marshmallow to handle schemas for my API. On endpoints that require creating or updating a model, it's often difficult to write an exception for every single possible error type. Therefore, I usually try to catch ValueErrors, IndexErrors, etc explicitly. However, as a last line of defense I do have an except Exception as e. This is to catch and document any exception that I may not know of. Ideally, this ends up catching library defined exceptions that do not inherit from a standard defined exception or inherit from Exception directly. I haven't hit this line yet on any of my views, but when I do I'll know exactly what exception I need to catch.
Writing
except Exception as e:
is clueless Python. If you're checking for something that went wrong in the outside world, you catch EnvironmentError. Catching Exception catches far too much, including syntax errors. It's sometimes useful to catch Exception at the top level of a program, log an error, and restart, but not in interior code.Note how useless the examples in the article are. It's not like someone is trying to handle all the things that can go wrong in a network connection, or in nested code where you have a network connection and a database transaction open at the same time, either can fail, and you have to unwind properly.
Typed language are fine, but this semi-checked addition of types to Python is a mess. Python doesn't need this. I'm in favor of design by contract, typing, and assertions, but not in this broken semi-optional way.
Stop Guido before he kills again.
Python is probably the best type declaration free language around. Trying to make it into something else damages the language. Python has become uncool, though, and so "cool features" are being added that don't quite fit.
These changes to Python are so big that this should have been called Python 4. But if Guido had done that, the reply from the big users would have been "Hell, no, we won't go!".
At first I was reluctant of the syntax, after a while I got used to it. Function definitions look a lot like Rust ones and do not require the endless docstrings just to document the type of the expected parameters anymore.
That's partly because we tend to use the same types for everything. For instance in a spreadsheet you can subtract a column number from a row number and get no complaints even though the difference between the two quite likely makes no sense. If you have a separate type for row numbers and column numbers such mistakes can be caught.
What you probably meant: This is where being strongly typed helps. Python is and always has been strongly typed.
http://mypy.readthedocs.io/en/latest/cheat_sheet_py3.html#st...
I'm not happy seeing language designers introducing strong or optional typing in languages that didn't have it, but I understand that their goals are different from the goals of the developers that use their languages. I'd say leave the core of Python (and Ruby [1]) alone: if we picked those dynamically typed languages in the last 25 years (they're that old) it means we like them so. We can use plenty of other languages if we really need types.
[1] https://blog.heroku.com/ruby-3-by-3 "Matz: ... the third major goal of the Ruby 3 is adding some kind of static typing whille keeping the duck typing, so some kind of structure for soft-typing or something like that. The main goal of the type system is to detect errors early. So adding this kind of static type check or type interfaces does not affect runtime."
So you get a string, and you want to pass it unmodified to something that expects a string? The static typing answer is simple: Your variable is a string! How does that slow you down, or cost your customers a single cent?
> "static typing only catches trivial errors"
To be honest I've not seen that sentiment very often, and it's definitely not something I agree with.
typecheck [0] is one (which can also run-time enforce the check) used like:
import typecheck as tc
def logathing(
dest: tc.hasattrs('write'),
thing: tc.any(int, float, str),
prefix: tc.optional(str)=None
):
dest.write(prefix + str(thing) if prefix else str(thing))
[0] - https://github.com/prechelt/typecheck-decoratorMoreover, if you would think a bit you would realize that the world around you is duck-typed. At least at the level of proteins.
One more thing. Every ontological attempt to use naive categories would fail and end up in duck-typing-like approach, because it reflects how the mother nature is.
It means it means there's no right or wrong way to do it, everything's subjective. Which is actually the exact opposite of the Python philosophy!
There is however an Any type which you can use for things you don't need enforced
Yes, and if I wanted type annotations to stop my program from working I wouldn't be using Python
Enforcing types is exactly what Python IS NOT about. Because of Duck Typing and everything else
So this is not "postmodern error handling" this is "let's code Java in something else and pat ourselves in the back"
Do you want to check errors in "compile time"? Use Pylint. It does the right thing
But for larger projects type checking is valuable. Types introduce additional contracts between components to manage and control the overall complexity of the system.
For small scripts and self contained applications I regard type checking as a burden. For larger projects not.
Pylint is a valuable tool to detect typical errors but does not check types. Regard a function which returns the sum of two given arguments. It will work with both arguments being integers and for both being strings. PyLint will not complain here, but if your code uses this result you might trigger errors much later during progam execution which are hard to detect or understand without type checking.
Wrong solution to the wrong problem. Break that too large for duck typing fucking mess into smaller independent components with well defined and enforced interfaces.
"Well defined and enforced interfaces"? That sounds like a job for static typing!
But seriously, that's exactly what types are good for: defining and enforcing an interface.
Pylint has nothing to do with catching type errors. It catches problems with code style.
I don't find the code in this blog post convincing, but there are reasons to write type-safe code.
No, it does catch type errors, for example accessing methods that are not present in the object
> but there are reasons to write type-safe code.
Yes, and there are lots of languages that allow you that
lots of abuse of error handling apparently just to have a fetch and parser in the same method?
why not have one promise of a fetch and then a promise of a successful parse?
http://www.telegraph.co.uk/news/2016/06/10/michael-goves-gui...
These days, the liberal arts generally relate to the humanities: language (e.g. English degree in the USA), fine arts, history, anthropology, sociology, philosophy, etc. It's the study of people and groups of people, instead of the physical world and the laws that operate on the physical world independently of the people that occupy it.