Hacker News new | comments | show | ask | jobs | submit login

Checking for empty strings can be done with len(mystring)==0 for this reason. In many other languages this method is standard and recommended practice.

Relying on implicit conversions is just sloppy. What if that variable was never supposed to be None in the first place. Better with an exception than continuing with corrupt data.

Remember another python motto: Explicit is better than implicit.




> Checking for empty strings can be done with len(mystring)==0 for this reason.

`len` blows up on None, so this blows up completely instead of just failing.

> Relying on implicit conversions is just sloppy.

There is no implicit conversion. Truthiness is a protocol, it does not convert anything anywhere.


> `len` blows up on None, so this blows up completely instead of just failing

That's the whole point! As I said, Better with an exception than continuing with corrupt data. Or maybe I should say unsupported data type rather than corrupt data.


At the point where you are doing your validation (or where you are doing the actual work with the variable) you can make that decision.

It's entirely possible that upstream code is content with any type as long as it's coercible. A lot of Python code just wants an iterable, for example, or something that can be coerced to a string.

It's definitely possible to have a situation where you need a string specifically (or an integer specifically), but it's generally better to have your code coerce the data whenever possible so as to allow for more logical code.

e.g. 's.send(str(object))' (if object has a relevant __str__()) makes perfect sense in code. You don't necessarily need a string, you just need something that can behave as a string in a sensible manner.

You also end up with scenarios where None is a 'valid value' in e.g. the SQL sense of 'value not specified'; for example, company_name might be '' (empty string provided) or None (no value provided); either way company_name is Falsey, and your logic should work the same.


If you need to differentiate between the empty string and None, you can, but in most situations the difference isn't important. E.g., would you ever actually display the values differently? Exaggerated explicitness can be misleading. E.g., if a year from now someone is making some changes, should they really be distracted by the fact that you've used 3 different if/else cases for the same semantic result?




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: