3 ms·
What you really want in this case is a way to overload the "." operator. If it were just an alias for call you could change None to respond to call on an undef
by Periodic 16y ago
What you really want in this case is a way to overload the "." operator. If it were just an alias for call you could change None to respond to call on an undefined method with None. That would sort of short-circuit the chain and avoid these errors.
It might require a few changes elsewhere as you would be getting None where you used to get an error, but relying on the error might have been some lazy programming to begin with.
- njharman 16y agoRather than localizing change to one api and requiring explicit effort to do so. That makes the change global and transparent, affecting all code (your code, std lib, 3rd party lib). It's really, really not what you want. Or at least not what the poor guy who has to maintain your poorly monkey patched code.
- jerf 16y agoNot in Python, because you wouldn't globally override it. You would just override the __getattr__ of the appropriate objects and be done with it, and nothing else would be affected. If you want it to be isolated a bit of work with "with" would make it easy. Though I would go an entirely different direction, personally, something like: f = self.find result = maybe_apply((f, ('table', {'class': ...})), (f, ('td', {'class': 'elem'})), (f, ('input',)), (self.get, ('name',))) Explicit is better than implicit. For bonus points, the "query" is now reusable and programmatically manipulable, which in my experience outweighs the ugly factor.
- bad_user 16y agoWhat do you mean by "reusable"? You're basically using Python as if it were Lisp, which is kind of ugly :)
- jerf 16y agoThe "qeury" has been reified as data. Now you can do whatever you want to it, including assign it to a variable. Sometimes the ugly tradeoff is OK, even in Python. In this case it is still less ugly than the code it is replacing, if you write correct code. Doing one little piddly-ass thing (running one method), then copy/pasting in the same four lines of error handling after every single one, well, it may be aesthetically pleasing on your screen but it's far uglier than what I've shown. Python has many advantages, but it isn't perfect.
- jey 16y agoNo, what you really want is for BeautifulSoup to do the sane thing and return an empty collection instead of None. It makes no sense to special-case the empty resultset case to return None.