
Dear Python-Ideas, (New here... hope this idea contributes something!) Several times I've had to implement a silly function that converts the odd environment variable (or some other value from the outside world that, perforce, comes in as a string) to the boolean it actually represents. I say "silly" because, for other commonly-needed types of primitive values, we have concise, idiomatic ways to convert them from strings, leaving no need for wheel reinvention: int(os.getenv('NUM_FJORDS')) float(os.getenv('PRICE_LIMBURGER')) etc. So I thought it might be nice if we could do something like this for booleans, too: Python 3.6.0a1+ (default:0b18f7d262cc+, Jun 12 2016, 18:21:54) [GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin Type "help", "copyright", "credits" or "license" for more information.
I seized the opportunity to work up my first (tiny) patch for CPython which implements this, along with tests (please see attached patch, which applies cleanly against current tip). Is there any interest in this? If so, I'd be happy to make it work for bytes too, or to make any other changes that would help get it landed. Thanks for your consideration, and looking forward to your feedback. Josh

On Sun, Jun 12, 2016 at 7:53 PM <jab@math.brown.edu> wrote:
bool.from_config_str('false') False
Why put the word "config" in the method name rather than just ``bool.from_str``? Why not just check for the truth values? config = 'False' try: value = bool(float(config)) except (TypeError, ValueError): value = config.casefold() == 'true' I agree it's frustrating to have the 4 lines. Perhaps this is yet another case that would be improved by exception-catching expressions (PEP 463)? Unless those 4 lines occur very frequently, this feels like a bit too special-case for a bool method. It feels more like it's part of a library offering environment or config utilities.

On 6/12/2016 7:52 PM, jab@math.brown.edu wrote:
We already can, with much more flexibility. See below.
This is all specific to English.
bool.from_config_str('0') False
Duplicates bool(int('0')). Ditto for '1'.
bool.from_config_str('') False
Duplicates bool('').
bool.from_config_str('1') True
These collectively duplicate "s in {'True', 'true', '1'}" One can use any set of strings to be mapped to True. The set can be reduced by lowercasing s. For an entry form, one might convert with "man = sex.lower() in {'m', 'man', 'male'}". One might even decide that "man = sex.lower.beginswith('m') is good enough. For standard .cfg configuration files, configparser.RawConfigParser has this class attribute and method. # Possible boolean values in the configuration. BOOLEAN_STATES = {'1': True, 'yes': True, 'true': True, 'on': True, '0': False, 'no': False, 'false': False, 'off': False} def _convert_to_boolean(self, value): """Return a boolean value translating from other types if necessary. """ if value.lower() not in self.BOOLEAN_STATES: raise ValueError('Not a boolean: %s' % value) return self.BOOLEAN_STATES[value.lower()] One can customize this for any langauge or application. A bool function would need duplicate attribute. -- Terry Jan Reedy

Hi Josh, and welcome! On Sun, Jun 12, 2016 at 07:52:28PM -0400, jab@math.brown.edu wrote: [...]
You have certainly found a need, but tempting as it is, I don't believe it should be in the standard library or a builtin. While it is true that nearly everyone will, at some point, want to convert human-readable strings to bools, the details of how and what they do are too individual. Some people will want to treat: true yes 1 on false no 0 off as true and false values, while others will have other ideas: vérité oui si wahr верный ja да aus ab unwahr etc. The point is, we cannot assume that all Python users will expect "yes" to map to True, and "no" to map to False. Since config files are generally written in the end-user's natural language, we can't even expect them to want "true" to map to True. But I do think that this is a great candidate for a utility function in your own personal toolbox. There's no need for it to be in the *standard* library when it can be in your own *personal* library. -- Steve

jab@math.brown.edu writes:
(New here... hope this idea contributes something!)
Thank you, I think you have indeed contributed here.
The obvious (to me) place to look for this is the ‘configparser’ module <URL:https://docs.python.org/3/library/configparser.html> in the standard library. That has functionality to read text, integer, or boolean values. (I am also a bit baffled to see some respondents in this thread expressing the notion there is no consensus on what input text should convert to a Boolean. The ‘configparser’ module is an obvious touchstone here for other Python behaviour, IMO.)
Is there any interest in this? If so, I'd be happy to make it work for bytes too, or to make any other changes that would help get it landed.
Perhaps the most obvious way to expose this functionality is as public functions on the ‘configparser’ module. Re-factor the existing functions to public functions, and expose those as part of the ‘configparser’ API. That way, any code could use them directly from the module regardless of whether a specific-format file were involved. -- \ “Science doesn't work by vote and it doesn't work by | `\ authority.” —Richard Dawkins, _Big Mistake_ (The Guardian, | _o__) 2006-12-27) | Ben Finney

On Mon, Jun 13, 2016 at 02:52:07PM +1000, Ben Finney wrote:
To be honest, I had forgotten about configparser. But I stand by my earlier comments: in this 21st century globally-connected world, to expect all users to write "yes" in a config file when they mean "oui" or "ja" is unacceptable. configparser works because the RawConfigParser class doesn't hard-code a list of strings, it sets an attribute BOOLEAN_STATES which can be overridden by instances. -- Steve

2016-06-13 8:21 GMT+02:00, Steven D'Aprano <steve@pearwood.info>:
Philosophical question which you are bringing is interesting! :) Are keywords: "for, while, if, try, catch" good enough for globally-connected world in 21st century? Would be better or worse for python ecosystem to have possibility to write for example: #!language:fr pour i en gamme(3): publier(i) Maybe in second fourth of 21 century, when we will have intelligent editors able automatically translate this to national (or international) python it could be strong idea? Or it's better to keep this simple in international/english mode? Not to build babel tower?

On Mon, Jun 13, 2016 at 06:12:30PM +0200, Pavol Lisy wrote:
Localising Python to a non-English variant has already been done at least once seriously: http://www.chinesepython.org/english/english.html http://www.reganmian.net/blog/2008/11/21/chinese-python-translating-a-progra... I'm pretty sure this is just intended as proof-of-concept: http://www.fiber-space.de/EasyExtend/doc/teuton/teuton.htm And if you really want to be silly, there's always LikePython: http://www.staringispolite.com/likepython/ The idea of localisation does come with solid precedents: - The ALGOL 68 standard allowed for localised versions, and at least one such version became the GOST/ГОСТ standard in the USSR. - Microsoft Office macro language is localised. - In the 1990s, Apple's Hyperscript and Applescript languages could be localised. - 4th Dimension localised its keywords to French or German. - There were various versions of BASIC localised to Chinese and other languages. - Perl's parser can be modified at runtime to support not just keyword localisation, but changing the grammar as well. Of course Perl hackers used this to support Latin and Klingon. -- Steve

Steven D'Aprano writes:
The idea of localisation does come with solid precedents:
But the argument against localization of machine-parsed code (which would include configs) has solid precedents from the days of PEP 263 implementation. There the issue was the language of comments (which aren't even machine-parsed!) Several prominent developers with impeccable "global" credentials related anecdotes involving comments that were unreadable to the rest of the team when the author left, as well as one ridiculous case where the entire dev team of one nationality left to form a startup or something, and were replaced by a new team of a different nationality. As a not-so-prominent developer, I can testify to translating several hundred lines of Japanese comments in XEmacs sources because the authors had disappeared and I was the only Japanese reader in the core. Localization for educational purposes at the compulsory education level may make sense (although for children under the age of 12 it probably has little value, because they absorb new words and whole new languages very quickly -- OTOH, their teachers already have withered neurons at ages as low as 23). Other than that kind of use case, if localization is so important, make a configuration app and localize that, I think. Steve

On 06/13/2016 03:21 AM, Steven D'Aprano wrote:
Users (the chunk of meat type) should not have access to configuration files. Developers should know the human language the project is being developed in (and it should be English). As far as a configuration file goes, supporting only 1 and 0 for true and false is good enough. This "globally-connected paranoia" would justify having rotating = ee In public codebases. What is ee? True? False? A number?

On Jun 12, 2016, at 4:52 PM, jab@math.brown.edu wrote:
Previous discussion about the said patch: http://bugs.python.org/issue25243 <http://bugs.python.org/issue25243> The most robust solution here, as Raymond suggests on the issue, is to define an application-level dictionary and use that. In this case you always know what values you support and you control what they are. This is literally a few lines of code. The configparser implementation is 6 without the docstring. Let me explain why introducing your patch is not as easy as it might seem. The problem with adding any variant of `from_config_str` to the `bool` type is that there is no clear pre-defined standard to follow here. That means this would likely open a new stream of bike shedding about what should and should not be part of the new API. Some people would like to be able to plug into this to add their own values. Others would like to read the existing dictionaries to reuse them in some library. Somebody would suggest `from_config_bytes()`. And so on, and so on. All in all, this adds a maintenance burden on the current and future CPython contributors. All of which are ultimately volunteers. To put this into perspective, look at the `itertools` documentation. It's split between describing what the library implements and an “Itertools Recipes” section that includes over two dozens of ~3-liners that the users might want to use in their programs. This form of documentation sends a message that the user is free to compose existing functionality however they want. It also sends a subtler message that not all three-liners have a place in the standard library, let alone the language. In the days of robust PyPI and ubiquitous `pip`, it’s easy to fill gaps yourself, in which case your solution is also usable with older versions of Python. Summing up, thank you for your patch but I don’t think it is going to get accepted. I hope you understand. Don’t let that discourage you from tinkering further with CPython. -- Lukasz Langa | Facebook Production Engineer | The Ministry of Silly Walks

On Mon, Jun 13, 2016 at 3:19 AM, Łukasz Langa <lukasz@langa.pl> wrote:
Previous discussion about the said patch: http://bugs.python.org/issue25243
((( I would have linked to that, but: - That's actually a different patch, and an inaccurate discussion of it, to boot. For one, in an effort to avoid exactly your bike shedding concerns, I specifically didn't include "on"/"off" or "yes"/"no" this time (which I wouldn't have included originally, if it weren't for the built-in configparser module's using them in getboolean().) - The mention of the configparser module in that discussion ends up being distracting, confusing the issue, and taking away from the productive discussion of it I hoped to have here. - Case in point, Raymond misunderstood the original patch, and then never got a chance to respond to my clarifications. So I was just trying to save people here from wasting time reading an out-of-date patch and a confusing and inaccurate discussion of it. ))) -- I know this would only save us from each having to rewrite the same few-line function. And I know there can be a tradeoff in introducing a new API like this. If it's just not possible to narrow the scope of this enough to make it worth it (e.g. would just accepting "True" or "False", so we offered a round-trip from str(some_bool), settle this?), I'll leave it at that. But if anyone has any other ideas or feels it's worth discussing further, I'd be happy to. Thanks for your consideration! Josh

I do believe something like that, but with a better name should exist. I have seen countless implementations for the same thing done over and over again. The whole point of a good standard library is to prevent repetition. The funniest thing is that I personally use distutils.util.strtobool. The fact that the same concept exists twice even in the standard library and I wouldn't be surprised to see third or fourth implementation somewhere in there, should be somewhat alarming. Perhaps a utility function module, much like distutils.util should be introduced. distutils.dir_util.mkpath is also something I often use. Maybe even renaming that forgotten module and raising awareness is the solution.Another nice example is the itertools recipes. Things that people just re-implement over and over again. tl;dr: My suggestion is a utility module containing many implemented recipes shortening many commonly used patterns. The only question is how to prevent over-extending it with lots of niche and less-used ones. On Mon, Jun 13, 2016 at 10:33 PM <jab@math.brown.edu> wrote:

On Mon, Jun 13, 2016 at 5:32 PM Bar Harel <bzvi7919@gmail.com> wrote:
The whole point of a good standard library is to prevent repetition.
Certain kinds of repetition, yes. Some code looks almost exactly the same, but the slight differences make it hard to generalize as a function. In those cases, it's better for the language to provide some simple tools that can be composed to get the job done. In this case, we have ``value = config in strings_that_mean_true`` which solves the category of problem quite nicely. The fact that the same concept exists twice even in the standard library
The repetition is that each case might have a different standard for what strings are truthy and whether to raise an error if the string is an unexpected value.
Some possible criteria for evaluating the benefit of a function/class: - the code pattern it replaces is very common in stdlib and major projects - the code pattern it replaces is a frequent source of bugs, even if rare - the code pattern it replaces is hard to write, even if usually correct - the code pattern it replaces is hard to read, even if rare and easy to write Sometimes copy-paste-tweak is OK.

Thanks for the feedback. I like your criteria suggestions btw. The repetition is that each case might have a different standard for what
strings are truthy and whether to raise an error if the string is an unexpected value.
Well, both configparser and strtobool evaluate the same strings as True and False, and both raise an exception but I see what you're saying. I personally feel that a new utility module has space much like itertool's common recipes and their function "equivalent" explanations. Heck, even itertool itself is basically a utility module, but another option is creating a wiki page similar to PerformanceTips <https://wiki.python.org/moin/PythonSpeed/PerformanceTips> in wiki.python.org. It won't require even a single line of code and being marked as "suggested guidelines" from the python community may be highly beneficial. What do you think of that? :-) On Tue, Jun 14, 2016 at 1:09 AM Michael Selik <michael.selik@gmail.com> wrote:

On Mon, Jun 13, 2016 at 1:52 AM, <jab@math.brown.edu> wrote:
My proposal I use everyday: foo = os.environ.get('FOO', DEFAULT_FOO).lower() in ('1', 'true', 'yes') It's easy, concise and powerful, allow to specify what do you think is true in that case. -- Marcin Sztolcman :: http://urzenia.net/ :: http://sztolcman.eu/

On Jun 12, 2016, at 07:52 PM, jab@math.brown.edu wrote:
FWIW, in some projects I use lazr.config, which has (among other type conversions) an as_boolean() method which does: value = value.lower() if value in ('true', 'yes', '1', 'on', 'enabled', 'enable'): return True if value in ('false', 'no', '0', 'off', 'disabled', 'disable'): return False raise ValueError('Invalid boolean value: %s' % value) I understand the problem with adding this in a generic method on the bool type, so I'm just mentioning this in case lazr.config.as_boolean() is useful to you. Cheers, -Barry

On Sun, Jun 12, 2016 at 7:53 PM <jab@math.brown.edu> wrote:
bool.from_config_str('false') False
Why put the word "config" in the method name rather than just ``bool.from_str``? Why not just check for the truth values? config = 'False' try: value = bool(float(config)) except (TypeError, ValueError): value = config.casefold() == 'true' I agree it's frustrating to have the 4 lines. Perhaps this is yet another case that would be improved by exception-catching expressions (PEP 463)? Unless those 4 lines occur very frequently, this feels like a bit too special-case for a bool method. It feels more like it's part of a library offering environment or config utilities.

On 6/12/2016 7:52 PM, jab@math.brown.edu wrote:
We already can, with much more flexibility. See below.
This is all specific to English.
bool.from_config_str('0') False
Duplicates bool(int('0')). Ditto for '1'.
bool.from_config_str('') False
Duplicates bool('').
bool.from_config_str('1') True
These collectively duplicate "s in {'True', 'true', '1'}" One can use any set of strings to be mapped to True. The set can be reduced by lowercasing s. For an entry form, one might convert with "man = sex.lower() in {'m', 'man', 'male'}". One might even decide that "man = sex.lower.beginswith('m') is good enough. For standard .cfg configuration files, configparser.RawConfigParser has this class attribute and method. # Possible boolean values in the configuration. BOOLEAN_STATES = {'1': True, 'yes': True, 'true': True, 'on': True, '0': False, 'no': False, 'false': False, 'off': False} def _convert_to_boolean(self, value): """Return a boolean value translating from other types if necessary. """ if value.lower() not in self.BOOLEAN_STATES: raise ValueError('Not a boolean: %s' % value) return self.BOOLEAN_STATES[value.lower()] One can customize this for any langauge or application. A bool function would need duplicate attribute. -- Terry Jan Reedy

Hi Josh, and welcome! On Sun, Jun 12, 2016 at 07:52:28PM -0400, jab@math.brown.edu wrote: [...]
You have certainly found a need, but tempting as it is, I don't believe it should be in the standard library or a builtin. While it is true that nearly everyone will, at some point, want to convert human-readable strings to bools, the details of how and what they do are too individual. Some people will want to treat: true yes 1 on false no 0 off as true and false values, while others will have other ideas: vérité oui si wahr верный ja да aus ab unwahr etc. The point is, we cannot assume that all Python users will expect "yes" to map to True, and "no" to map to False. Since config files are generally written in the end-user's natural language, we can't even expect them to want "true" to map to True. But I do think that this is a great candidate for a utility function in your own personal toolbox. There's no need for it to be in the *standard* library when it can be in your own *personal* library. -- Steve

jab@math.brown.edu writes:
(New here... hope this idea contributes something!)
Thank you, I think you have indeed contributed here.
The obvious (to me) place to look for this is the ‘configparser’ module <URL:https://docs.python.org/3/library/configparser.html> in the standard library. That has functionality to read text, integer, or boolean values. (I am also a bit baffled to see some respondents in this thread expressing the notion there is no consensus on what input text should convert to a Boolean. The ‘configparser’ module is an obvious touchstone here for other Python behaviour, IMO.)
Is there any interest in this? If so, I'd be happy to make it work for bytes too, or to make any other changes that would help get it landed.
Perhaps the most obvious way to expose this functionality is as public functions on the ‘configparser’ module. Re-factor the existing functions to public functions, and expose those as part of the ‘configparser’ API. That way, any code could use them directly from the module regardless of whether a specific-format file were involved. -- \ “Science doesn't work by vote and it doesn't work by | `\ authority.” —Richard Dawkins, _Big Mistake_ (The Guardian, | _o__) 2006-12-27) | Ben Finney

On Mon, Jun 13, 2016 at 02:52:07PM +1000, Ben Finney wrote:
To be honest, I had forgotten about configparser. But I stand by my earlier comments: in this 21st century globally-connected world, to expect all users to write "yes" in a config file when they mean "oui" or "ja" is unacceptable. configparser works because the RawConfigParser class doesn't hard-code a list of strings, it sets an attribute BOOLEAN_STATES which can be overridden by instances. -- Steve

2016-06-13 8:21 GMT+02:00, Steven D'Aprano <steve@pearwood.info>:
Philosophical question which you are bringing is interesting! :) Are keywords: "for, while, if, try, catch" good enough for globally-connected world in 21st century? Would be better or worse for python ecosystem to have possibility to write for example: #!language:fr pour i en gamme(3): publier(i) Maybe in second fourth of 21 century, when we will have intelligent editors able automatically translate this to national (or international) python it could be strong idea? Or it's better to keep this simple in international/english mode? Not to build babel tower?

On Mon, Jun 13, 2016 at 06:12:30PM +0200, Pavol Lisy wrote:
Localising Python to a non-English variant has already been done at least once seriously: http://www.chinesepython.org/english/english.html http://www.reganmian.net/blog/2008/11/21/chinese-python-translating-a-progra... I'm pretty sure this is just intended as proof-of-concept: http://www.fiber-space.de/EasyExtend/doc/teuton/teuton.htm And if you really want to be silly, there's always LikePython: http://www.staringispolite.com/likepython/ The idea of localisation does come with solid precedents: - The ALGOL 68 standard allowed for localised versions, and at least one such version became the GOST/ГОСТ standard in the USSR. - Microsoft Office macro language is localised. - In the 1990s, Apple's Hyperscript and Applescript languages could be localised. - 4th Dimension localised its keywords to French or German. - There were various versions of BASIC localised to Chinese and other languages. - Perl's parser can be modified at runtime to support not just keyword localisation, but changing the grammar as well. Of course Perl hackers used this to support Latin and Klingon. -- Steve

Steven D'Aprano writes:
The idea of localisation does come with solid precedents:
But the argument against localization of machine-parsed code (which would include configs) has solid precedents from the days of PEP 263 implementation. There the issue was the language of comments (which aren't even machine-parsed!) Several prominent developers with impeccable "global" credentials related anecdotes involving comments that were unreadable to the rest of the team when the author left, as well as one ridiculous case where the entire dev team of one nationality left to form a startup or something, and were replaced by a new team of a different nationality. As a not-so-prominent developer, I can testify to translating several hundred lines of Japanese comments in XEmacs sources because the authors had disappeared and I was the only Japanese reader in the core. Localization for educational purposes at the compulsory education level may make sense (although for children under the age of 12 it probably has little value, because they absorb new words and whole new languages very quickly -- OTOH, their teachers already have withered neurons at ages as low as 23). Other than that kind of use case, if localization is so important, make a configuration app and localize that, I think. Steve

On 06/13/2016 03:21 AM, Steven D'Aprano wrote:
Users (the chunk of meat type) should not have access to configuration files. Developers should know the human language the project is being developed in (and it should be English). As far as a configuration file goes, supporting only 1 and 0 for true and false is good enough. This "globally-connected paranoia" would justify having rotating = ee In public codebases. What is ee? True? False? A number?

On Jun 12, 2016, at 4:52 PM, jab@math.brown.edu wrote:
Previous discussion about the said patch: http://bugs.python.org/issue25243 <http://bugs.python.org/issue25243> The most robust solution here, as Raymond suggests on the issue, is to define an application-level dictionary and use that. In this case you always know what values you support and you control what they are. This is literally a few lines of code. The configparser implementation is 6 without the docstring. Let me explain why introducing your patch is not as easy as it might seem. The problem with adding any variant of `from_config_str` to the `bool` type is that there is no clear pre-defined standard to follow here. That means this would likely open a new stream of bike shedding about what should and should not be part of the new API. Some people would like to be able to plug into this to add their own values. Others would like to read the existing dictionaries to reuse them in some library. Somebody would suggest `from_config_bytes()`. And so on, and so on. All in all, this adds a maintenance burden on the current and future CPython contributors. All of which are ultimately volunteers. To put this into perspective, look at the `itertools` documentation. It's split between describing what the library implements and an “Itertools Recipes” section that includes over two dozens of ~3-liners that the users might want to use in their programs. This form of documentation sends a message that the user is free to compose existing functionality however they want. It also sends a subtler message that not all three-liners have a place in the standard library, let alone the language. In the days of robust PyPI and ubiquitous `pip`, it’s easy to fill gaps yourself, in which case your solution is also usable with older versions of Python. Summing up, thank you for your patch but I don’t think it is going to get accepted. I hope you understand. Don’t let that discourage you from tinkering further with CPython. -- Lukasz Langa | Facebook Production Engineer | The Ministry of Silly Walks

On Mon, Jun 13, 2016 at 3:19 AM, Łukasz Langa <lukasz@langa.pl> wrote:
Previous discussion about the said patch: http://bugs.python.org/issue25243
((( I would have linked to that, but: - That's actually a different patch, and an inaccurate discussion of it, to boot. For one, in an effort to avoid exactly your bike shedding concerns, I specifically didn't include "on"/"off" or "yes"/"no" this time (which I wouldn't have included originally, if it weren't for the built-in configparser module's using them in getboolean().) - The mention of the configparser module in that discussion ends up being distracting, confusing the issue, and taking away from the productive discussion of it I hoped to have here. - Case in point, Raymond misunderstood the original patch, and then never got a chance to respond to my clarifications. So I was just trying to save people here from wasting time reading an out-of-date patch and a confusing and inaccurate discussion of it. ))) -- I know this would only save us from each having to rewrite the same few-line function. And I know there can be a tradeoff in introducing a new API like this. If it's just not possible to narrow the scope of this enough to make it worth it (e.g. would just accepting "True" or "False", so we offered a round-trip from str(some_bool), settle this?), I'll leave it at that. But if anyone has any other ideas or feels it's worth discussing further, I'd be happy to. Thanks for your consideration! Josh

I do believe something like that, but with a better name should exist. I have seen countless implementations for the same thing done over and over again. The whole point of a good standard library is to prevent repetition. The funniest thing is that I personally use distutils.util.strtobool. The fact that the same concept exists twice even in the standard library and I wouldn't be surprised to see third or fourth implementation somewhere in there, should be somewhat alarming. Perhaps a utility function module, much like distutils.util should be introduced. distutils.dir_util.mkpath is also something I often use. Maybe even renaming that forgotten module and raising awareness is the solution.Another nice example is the itertools recipes. Things that people just re-implement over and over again. tl;dr: My suggestion is a utility module containing many implemented recipes shortening many commonly used patterns. The only question is how to prevent over-extending it with lots of niche and less-used ones. On Mon, Jun 13, 2016 at 10:33 PM <jab@math.brown.edu> wrote:

On Mon, Jun 13, 2016 at 5:32 PM Bar Harel <bzvi7919@gmail.com> wrote:
The whole point of a good standard library is to prevent repetition.
Certain kinds of repetition, yes. Some code looks almost exactly the same, but the slight differences make it hard to generalize as a function. In those cases, it's better for the language to provide some simple tools that can be composed to get the job done. In this case, we have ``value = config in strings_that_mean_true`` which solves the category of problem quite nicely. The fact that the same concept exists twice even in the standard library
The repetition is that each case might have a different standard for what strings are truthy and whether to raise an error if the string is an unexpected value.
Some possible criteria for evaluating the benefit of a function/class: - the code pattern it replaces is very common in stdlib and major projects - the code pattern it replaces is a frequent source of bugs, even if rare - the code pattern it replaces is hard to write, even if usually correct - the code pattern it replaces is hard to read, even if rare and easy to write Sometimes copy-paste-tweak is OK.

Thanks for the feedback. I like your criteria suggestions btw. The repetition is that each case might have a different standard for what
strings are truthy and whether to raise an error if the string is an unexpected value.
Well, both configparser and strtobool evaluate the same strings as True and False, and both raise an exception but I see what you're saying. I personally feel that a new utility module has space much like itertool's common recipes and their function "equivalent" explanations. Heck, even itertool itself is basically a utility module, but another option is creating a wiki page similar to PerformanceTips <https://wiki.python.org/moin/PythonSpeed/PerformanceTips> in wiki.python.org. It won't require even a single line of code and being marked as "suggested guidelines" from the python community may be highly beneficial. What do you think of that? :-) On Tue, Jun 14, 2016 at 1:09 AM Michael Selik <michael.selik@gmail.com> wrote:

On Mon, Jun 13, 2016 at 1:52 AM, <jab@math.brown.edu> wrote:
My proposal I use everyday: foo = os.environ.get('FOO', DEFAULT_FOO).lower() in ('1', 'true', 'yes') It's easy, concise and powerful, allow to specify what do you think is true in that case. -- Marcin Sztolcman :: http://urzenia.net/ :: http://sztolcman.eu/

On Jun 12, 2016, at 07:52 PM, jab@math.brown.edu wrote:
FWIW, in some projects I use lazr.config, which has (among other type conversions) an as_boolean() method which does: value = value.lower() if value in ('true', 'yes', '1', 'on', 'enabled', 'enable'): return True if value in ('false', 'no', '0', 'off', 'disabled', 'disable'): return False raise ValueError('Invalid boolean value: %s' % value) I understand the problem with adding this in a generic method on the bool type, so I'm just mentioning this in case lazr.config.as_boolean() is useful to you. Cheers, -Barry
participants (12)
-
Bar Harel
-
Barry Warsaw
-
Ben Finney
-
Bernardo Sulzbach
-
jab@math.brown.edu
-
Marcin Sztolcman
-
Michael Selik
-
Pavol Lisy
-
Stephen J. Turnbull
-
Steven D'Aprano
-
Terry Reedy
-
Łukasz Langa