On Tue, Oct 13, 2020 at 1:21 PM Christopher Barker <python...@gmail.com> wrote:
> On Tue, Oct 13, 2020 at 9:55 AM David Mertz <me...@gnosis.cx> wrote: > >> If you really want a snazzy highly-parameterized exception, write it >> yourself as a class factory. I won't particularly like the antipattern, >> but it's available now. >> >> if some_bad_thing: >> raise ExceptionMaker("BadStuffError", details, plus, more_details) >> >> Implementation of 'ExceptionMaker' left to readers. But it's possible to >> write once. >> > > raise ExceptionMaker.BadStuffError(details, plus, more_details) > > But here's where I am still completely confused. In order to catch that > Exception, you need know about it -- it's name, what parameters it uses, > etc. > And that will be potentially very far from the code that creates it. > Yeah, I thought of that. I think the class factory would need to monkey-patch the global namespace. However, there's already a really clear way of "monkey-patching the global namespace": class BadStuffError(Exception): pass Sure, you can accomplish the same thing by overloading .__getattr__(). But the usual means is pretty nice. The OP has stated that all making an Exception class does is create a name > -- which is true (though the other thing it does is put that name in a > class hierarchy) -- but the thing is -- that's very useful! In fact, I > can't see how you could do this at all without creating a name somewhere > that it could be accessed from elsewhere. > Well, technically you could memoize calls to ExceptionMaker and have this work. In [11]: try: ...: raise ExceptionMaker("BadStuffError") ...: except ExceptionMaker("BadStuffError"): ...: print("caught") ...: caught I am NOT recommending this pattern. But it works in current Python.
_______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/2OC2HJV3B7EDXBWKTFQVHPOATUNUGZJM/ Code of Conduct: http://python.org/psf/codeofconduct/