Re: Style for docstring
On 26/04/2022 11.47, Rob Cliffe via Python-list wrote: > Well, de gustibus non est disputandum. For me, the switch from the > imperative mode to the descriptive mode produces a mild cognitive > dissonance. Disagree! When coding, to whom?what are you talking? When writing documentation - same question? This is the reason why (typically) coders are pretty bad at, or disagree with a need for, 'documentation' - and particularly documentation that doesn't fit inside a code-module! (no insult, pure observation) See earlier when I described taking a set of Requirements and progressively applying specific clauses or requirements to a function. One's thinking is in requirement-satisfaction-mode or 'design-mode'. Later, when implementing the function, one can work in 'coding-mode'. Separating tasks/roles removes the dissonance. No split-personality required! However, I know what you mean, and earlier today was writing to someone about why I may not bother with a docstring if I'm in coding-mode and wanting to 'keep going'. However, I see such as 'technical debt', justified only in the hope that when I do get back to it (presumably when the code is working, and I'm basking in the joys of (my own) success, I'll be in more of a 'documentation' frame of mind... (and pigs might fly!) > On 25/04/2022 23:34, Cameron Simpson wrote: >> On 23Apr2022 03:26, Avi Gross wrote: >>> We know some people using "professional" language make things shorteror >>> talk from a point of view different than others and often in >>> otherwise incomprehensible jargon. >>> If a programmer is taking about the algorithm that a function >>> implements, then, yes, they may write "scan" and "return". >>> But if they realize the darn documentation is for PEOPLE asking >>> how to use the darn thing, and want to write in more informal >>> and understandable English, I think it makes more sense to say >>> what the function does as in "scans" and importantly what it >>> "returns" to the user as a result. >> I'm in the imperative camp. But if I think the function requires some >> elaboration, _then_ I provide description: >> >> def f(x): >> ''' Return the frobnangle of `x`. >> >> This iterates over the internals of `x` in blah order >> gathering the earliest items which are frobby and composes a >> nangle of the items. >> ''' >> >> I very much like the concise imperative opening sentence, sometimes 2 >> sentences. Then the elaboration if the function isn't trivially obvious. >> >> Cheers, >> Cameron Simpson > -- Regards, =dn -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
Well, de gustibus non est disputandum. For me, the switch from the imperative mode to the descriptive mode produces a mild cognitive dissonance. Best wishes Rob Cliffe On 25/04/2022 23:34, Cameron Simpson wrote: On 23Apr2022 03:26, Avi Gross wrote: We know some people using "professional" language make things shorteror talk from a point of view different than others and often in otherwise incomprehensible jargon. If a programmer is taking about the algorithm that a function implements, then, yes, they may write "scan" and "return". But if they realize the darn documentation is for PEOPLE asking how to use the darn thing, and want to write in more informal and understandable English, I think it makes more sense to say what the function does as in "scans" and importantly what it "returns" to the user as a result. I'm in the imperative camp. But if I think the function requires some elaboration, _then_ I provide description: def f(x): ''' Return the frobnangle of `x`. This iterates over the internals of `x` in blah order gathering the earliest items which are frobby and composes a nangle of the items. ''' I very much like the concise imperative opening sentence, sometimes 2 sentences. Then the elaboration if the function isn't trivially obvious. Cheers, Cameron Simpson -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On 4/25/22 16:34, Cameron Simpson wrote: > On 23Apr2022 03:26, Avi Gross wrote: >> We know some people using "professional" language make things shorteror >> talk from a point of view different than others and often in >> otherwise incomprehensible jargon. >> If a programmer is taking about the algorithm that a function implements, >> then, yes, they may write "scan" and "return". >> But if they realize the darn documentation is for PEOPLE asking how to use >> the darn thing, and want to write in more informal and understandable >> English, I think it makes more sense to say what the function does as in >> "scans" and importantly what it "returns" to the user as a result. > > I'm in the imperative camp. But if I think the function requires some > elaboration, _then_ I provide description: Just as another data point, if nothing else to prove there will never be consensus :) - Google's style guide is pretty explicit about what they expect: > The docstring should be descriptive-style ("""Fetches rows from a Bigtable.""") rather than imperative-style ("""Fetch rows from a Bigtable."""). -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On 23Apr2022 03:26, Avi Gross wrote: >We know some people using "professional" language make things shorteror >talk from a point of view different than others and often in >otherwise incomprehensible jargon. >If a programmer is taking about the algorithm that a function implements, >then, yes, they may write "scan" and "return". >But if they realize the darn documentation is for PEOPLE asking how to use the >darn thing, and want to write in more informal and understandable English, I >think it makes more sense to say what the function does as in "scans" and >importantly what it "returns" to the user as a result. I'm in the imperative camp. But if I think the function requires some elaboration, _then_ I provide description: def f(x): ''' Return the frobnangle of `x`. This iterates over the internals of `x` in blah order gathering the earliest items which are frobby and composes a nangle of the items. ''' I very much like the concise imperative opening sentence, sometimes 2 sentences. Then the elaboration if the function isn't trivially obvious. Cheers, Cameron Simpson -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
Yes, Michael, a dictionary is an excellent way to represent a closed set of transitions which your permutations are. You examples use numerals but obviously a dictionary will allow transformations of anything that can be hashed which mostly is items that are not mutable. Of course for the purposes you may be using these permutations, accessing them may be done carefully as you need to have nothing else in the dictionary and must access all the keys and make sure you know which keys have already been visited from another item. Some other data structures may work better or faster on smaller examples. I think you have satisfied my curiosity and your main and only question really was on suggested wording of a Docstring. Now if only the Docstring idea was replaced by a Dictionary too! Things like: Dictstring = {"Purpose": "Text", "Args": "Text", "Return(s)": "Text", "Optional-Note": "Text", "French version": DocStringFrench} Too late to seriously change the language now! -Original Message- From: Michael F. Stemper To: python-list@python.org Sent: Sun, Apr 24, 2022 9:24 am Subject: Re: Style for docstring On 23/04/2022 12.43, Avi Gross wrote: > Given what you added, Michael, your function is part of a larger collection > of functions and being compatible with the others is a valid consideration. > Whatever you decide, would ideally be done consistently with all or most of > them. > And, of course, it others in the collection also can handle multiple ways to > specify a permutation, it may be simpler to have each call something like > as.permutation() that handlesmultiple forms and converts to the one easiest > for you to use. > I am not sure that is needed as I suspect the simplest storage is something > like a list: [0,3,2,4,5,6,7,1,9,8] but could also be shown with each cycle > as a sub-list or something like anumpy vector or a customized class. Since you ask, I'm using dictionaries as the internal representation. If you think about it, a python dictionary *is* a function from one finite set to another, mathematically. And a (finite) permutation is a bijection from a (finite) set to itself. For convenience, the module provides two methods of defining a permutation other than just entering a dictionary: >>> import PermGroups as pg >>> a = {'1':'2', '2':'1', '3':'3'} >>> b = pg.ParsePerm( '(12)(3)' ) >>> c = pg.ParseDomImg( '123', '213' ) >>> a==b True >>> b==c True >>> All of the other functions work on these dictionaries. I had thought about defining a permutation object, but the conceptual match between "dict" and "permutation" was too good to discard. > Clearly if you control the package and how it is used, errors from bad data > may not be a concern. An invalidly-constructed permutation will cause an exception, so the function won't return. >>> d = {'1':'2', '2':'2', '3':'3'} >>> pg.ValidateDict(d) False >>> If I was to do it over, I would have named this function something like IsValidPermutation(), hiding the internal representation as well as making the function's Boolean nature explicit. -- Michael F. Stemper No animals were harmed in the composition of this message. -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On 25/04/2022 01.24, Michael F. Stemper wrote: > On 23/04/2022 12.43, Avi Gross wrote: >> Given what you added, Michael, your function is part of a >> larger collection of functions and being compatible with the others >> is a valid consideration. Whatever you decide, would ideally be done >> consistently with all or most of them. >> And, of course, it others in the collection also can handle multiple >> ways to specify a permutation, it may be simpler to have each call >> something like as.permutation() that handlesmultiple forms and >> converts to the one easiest for you to use. >> I am not sure that is needed as I suspect the simplest storage is >> something like a list: [0,3,2,4,5,6,7,1,9,8] but could also be shown >> with each cycle as a sub-list or something like anumpy vector or a >> customized class. > > Since you ask, I'm using dictionaries as the internal representation. > If you think about it, a python dictionary *is* a function from one > finite set to another, mathematically. And a (finite) permutation is > a bijection from a (finite) set to itself. > > For convenience, the module provides two methods of defining a permutation > other than just entering a dictionary: > > >>> import PermGroups as pg > >>> a = {'1':'2', '2':'1', '3':'3'} > >>> b = pg.ParsePerm( '(12)(3)' ) > >>> c = pg.ParseDomImg( '123', '213' ) > >>> a==b > True > >>> b==c > True > >>> > > All of the other functions work on these dictionaries. > > I had thought about defining a permutation object, but the conceptual > match between "dict" and "permutation" was too good to discard. > >> Clearly if you control the package and how it is used, errors from bad >> data may not be a concern. > > An invalidly-constructed permutation will cause an exception, so > the function won't return. > > >>> d = {'1':'2', '2':'2', '3':'3'} > >>> pg.ValidateDict(d) > False > >>> > > If I was to do it over, I would have named this function something > like IsValidPermutation(), hiding the internal representation as > well as making the function's Boolean nature explicit. Yes, we live and learn! (but 'technical debt'...) Naming something based upon its implementation, eg ValidateDict(), rather than its purpose, is a definite no-no - and while I'm nit-picking, is that a function? (and thus validate_dict()) The idea of representing perms as dicts is good-thinking! Please review UserDict (https://docs.python.org/3/library/collections.html#collections.UserDict). Sub-classing UserDict gives the advantages of a dict, without some of the methods you don't want/need, and the ability to gather custom permutation-methods into the class. For a discussion about sub-classing dict or using UserDict, may I recommend Trey Hunner's analysis, aka "there's no such thing as a free lunch" (https://treyhunner.com/2019/04/why-you-shouldnt-inherit-from-list-and-dict-in-python/) Since then, we've been given (and I haven't had a reason to try it, yet) "PEP 589 – TypedDict: Type Hints for Dictionaries with a Fixed Set of Keys" which may offer an alternate approach. This comes with the advantage of 'compile-time' static analysis/checking (https://peps.python.org/pep-0589/). When I get around to experimenting with this, I'll be referring to "TypedDict vs dataclasses in Python" (https://dev.to/meeshkan/typeddict-vs-dataclasses-in-python-epic-typing-battle-onb) -- Regards, =dn -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On 24/04/2022 08.24, Michael F. Stemper wrote: On 23/04/2022 12.43, Avi Gross wrote: Given what you added, Michael, your function is part of a larger collection of functions and being compatible with the others is a valid consideration. Whatever you decide, would ideally be done consistently with all or most of them. And, of course, it others in the collection also can handle multiple ways to specify a permutation, it may be simpler to have each call something like as.permutation() that handlesmultiple forms and converts to the one easiest for you to use. I am not sure that is needed as I suspect the simplest storage is something like a list: [0,3,2,4,5,6,7,1,9,8] but could also be shown with each cycle as a sub-list or something like anumpy vector or a customized class. Since you ask, I'm using dictionaries as the internal representation. If you think about it, a python dictionary *is* a function from one finite set to another, mathematically. And a (finite) permutation is a bijection from a (finite) set to itself. For convenience, the module provides two methods of defining a permutation other than just entering a dictionary: >>> import PermGroups as pg >>> a = {'1':'2', '2':'1', '3':'3'} >>> b = pg.ParsePerm( '(12)(3)' ) >>> c = pg.ParseDomImg( '123', '213' ) >>> a==b True >>> b==c True >>> All of the other functions work on these dictionaries. I had thought about defining a permutation object, but the conceptual match between "dict" and "permutation" was too good to discard. Clearly if you control the package and how it is used, errors from bad data may not be a concern. An invalidly-constructed permutation will cause an exception, so the function won't return. The below was *not* intended to illustrate what I said above. It shows the validation function provided by the module. This allows the user to avoid the consequences of an invalidly-constructed permutation. (It's only for users who don't subscribe to "EAFP", of course.) >>> d = {'1':'2', '2':'2', '3':'3'} >>> pg.ValidateDict(d) False >>> If I was to do it over, I would have named this function something like IsValidPermutation(), hiding the internal representation as well as making the function's Boolean nature explicit. -- Michael F. Stemper Psalm 82:3-4 -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On 23/04/2022 12.43, Avi Gross wrote: Given what you added, Michael, your function is part of a larger collection of functions and being compatible with the others is a valid consideration. Whatever you decide, would ideally be done consistently with all or most of them. And, of course, it others in the collection also can handle multiple ways to specify a permutation, it may be simpler to have each call something like as.permutation() that handlesmultiple forms and converts to the one easiest for you to use. I am not sure that is needed as I suspect the simplest storage is something like a list: [0,3,2,4,5,6,7,1,9,8] but could also be shown with each cycle as a sub-list or something like anumpy vector or a customized class. Since you ask, I'm using dictionaries as the internal representation. If you think about it, a python dictionary *is* a function from one finite set to another, mathematically. And a (finite) permutation is a bijection from a (finite) set to itself. For convenience, the module provides two methods of defining a permutation other than just entering a dictionary: >>> import PermGroups as pg >>> a = {'1':'2', '2':'1', '3':'3'} >>> b = pg.ParsePerm( '(12)(3)' ) >>> c = pg.ParseDomImg( '123', '213' ) >>> a==b True >>> b==c True >>> All of the other functions work on these dictionaries. I had thought about defining a permutation object, but the conceptual match between "dict" and "permutation" was too good to discard. Clearly if you control the package and how it is used, errors from bad data may not be a concern. An invalidly-constructed permutation will cause an exception, so the function won't return. >>> d = {'1':'2', '2':'2', '3':'3'} >>> pg.ValidateDict(d) False >>> If I was to do it over, I would have named this function something like IsValidPermutation(), hiding the internal representation as well as making the function's Boolean nature explicit. -- Michael F. Stemper No animals were harmed in the composition of this message. -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On 23/04/2022 08.35, Michael F. Stemper wrote: > On 22/04/2022 14.59, Chris Angelico wrote: >> On Sat, 23 Apr 2022 at 05:56, Michael F. Stemper >> wrote: >>> >>> I'm writing a function that is nearly self-documenting by its name, >>> but still want to give it a docstring. Which of these would be >>> best from a stylistic point of view: >>> >>> >>> Tells caller whether or not a permutation is even. >>> >>> Determines if a permutation is even. (Alternative is that it's odd.) >>> >>> Returns True if permutation is even, False if it is odd. > > >> >> I'd go with the third one, but "Return" rather than "Returns". Or >> possibly "Test whether a permutation is even". > > "So let it be written. So let it be done." > >> That's just one opinion though, others may disagree :) > > Two for two. Thanks. I've always taken the PEP somewhat for granted (with belated thanks and respect to the authors and others who exerted effort (or would that be, efforts?) to publish the finished work. One of the things that I've taken-as-read, is WHY we use docstrings. That rationale is wider than Python. Like many others, I just brought that sort thinking with me. Have you noticed that the PEP doesn't discuss this? It has taken this thread to make me realise such. The elephant in the style room is PEP-008. It's quite old in 'Python-years'! As time went by, PEP-257 became relevant - and I don't recall which was 'chicken' and which 'egg', between the PEP and the docutils/help/etc tools which depend upon a level of docstring uniformity. No matter, together they represent a step of progress, after PEP-008. Since then we have added typing. Where once there was an extensive documentation system to clarify the use of parameters and the definition of return-values, now much of that can be done on the def-line (or equivalent). Another 'development' (I'd prefer 'natural progression') is that as computers have become more powerful and storage cheaper, we have been able to first justify, and now habitually, use longer identifier-names. This step of progress should enable more descriptive and readable code. So, we can consider that there are (now) three aspects which overlap, considerably: 1 the name of the function - descriptive and readable (see OP's assurance on this point) 2 typing - description and distinction of parameters and return-values 3 docstring - even more information about the function, how the author intends it be used, embedded assumptions, etc Thus, aren't there situations where a short, sharp, DRY, and SRP, function; once well-named and accurately typed, could stand on its own merits without a docstring. (yes, others will suck in their breath and start preparing a bon-fire, at the utterance of such 'heresy'...) We all hate 'boiler-plate', ie feeling forced to type stuff 'just because', and particularly when it seems like duplication/repetition (see recent thread(s) 'here' about __init__() and dataclasses). In fact, one reason why we have functions is to reduce/remove (code) duplication! So, why would we indulge in documental 'duplication' just-because we should?must have a docstring? While I'm tilting at windmills, wasn't option-2 the best? (ooh, those flames are starting to warm my feet...) Why? First, see other discussion about "imperatives". My habit is to take the Statement of Requirements and copy it into a brand-new __main__. As development proceeds, various details will be extracted and copied into function and class docstrings. The language of a specification should be imperative, ie you will *do* 'this'. A second reason, is that the docstring should document the function, which is subtly-different from describing the return-value (and that has become a task for typing anyway). (OK, the flames are getting-good, and it's time to break-out the marsh-mallows and crumpets...) So, 'nr2' describes what the function DOES! PS would you mind passing-over the fire-extinguisher? -- Regards, =dn -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
"return true iff this". I like this. jan On 23/04/2022, Stefan Ram wrote: > Rob Cliffe writes: >>I'm curious as to why so many people prefer "Return" to "Returns". > > The commands, er, names of functions, use the imperative mood > ("print", not "prints"). So, "return" aligns with that mood > as a paraphrase of such names. > > In Java, at one point, they decided to start to use the > third person at one point and then half-heartedly converted > all the documentation, as in > > |void println(boolean x) > |Prints a boolean and then terminate the line. > > , where they modified "print" but did not bother do modify > "terminate". > > And instead of "return true if this, false if not this", > I might be inclined to write "return true iff this". > > BTW: As a language element that helps to construct a boolean > expression from a file name, some languages, like SQL, use > "EXISTS", while others, like MS-DOS-batch, use "EXIST". > > > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On Fri, Apr 22, 2022 at 12:56 PM Michael F. Stemper < michael.stem...@gmail.com> wrote: > I'm writing a function that is nearly self-documenting by its name, > but still want to give it a docstring. Which of these would be > best from a stylistic point of view: > > >Tells caller whether or not a permutation is even. > >Determines if a permutation is even. (Alternative is that it's odd.) > >Returns True if permutation is even, False if it is odd. > > > (Before somebody suggests it, I'm not going to put six weeks' worth > of a course in group theory in there to help somebody who doesn't > know what those standard terms mean.) > Maybe try pydocstyle? -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
Given what you added, Michael, your function is part of a larger collection of functions and being compatible with the others is a valid consideration. Whatever you decide, would ideally be done consistently with all or most of them. And, of course, it others in the collection also can handle multiple ways to specify a permutation, it may be simpler to have each call something like as.permutation() that handlesmultiple forms and converts to the one easiest for you to use. I am not sure that is needed as I suspect the simplest storage is something like a list: [0,3,2,4,5,6,7,1,9,8] but could also be shown with each cycle as a sub-list or something like anumpy vector or a customized class. Clearly if you control the package and how it is used, errors from bad data may not be a concern. But like many Boolean return(s) it is always a problem how to deal with a third possibility. -Original Message- From: Michael F. Stemper To: python-list@python.org Sent: Sat, Apr 23, 2022 8:57 am Subject: Re: Style for docstring On 22/04/2022 21.58, Avi Gross wrote: > Python does have a concept of "truthy" that includes meaning for not just the > standard Booleans but for 0 and non-zero and the empty string and many more > odd things such as an object that defines __bool__ (). > But saying it returns a Boolean True/False valuesounds direct and simple and > informative enough if that is True. > What bothers me is the assumption that anyone knows not so muchjust group > theory but what the argument to the function looks like as a Python object > of some kind. > Does the function accept only some permutation object managed by a specific > module? Will it accept some alternate representation such as a list structure > or other iterator? That's a fair point. However, this function will be the 22nd one in a module for dealing with permutations and groups of permutations. The module has a lengthy docstring explaining the several ways provided to specify a permutation. That way, the same information doesn't need to be written twenty-plus times. > Obviously deeper details would normally be in a manual page or other > documentation but as "permutations" are likely not to be what most people > think about before breakfast, or even after, odd as that may seem, ... I see what you did there :-> -- Michael F. Stemper Psalm 94:3-6 -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On 22/04/2022 16.12, alister wrote: On Fri, 22 Apr 2022 14:36:27 -0500, Michael F. Stemper wrote: I'm writing a function that is nearly self-documenting by its name, but still want to give it a docstring. Which of these would be best from a stylistic point of view: for guidance I would sugest Pep257 as a start point which would suggest "Return True if permutation is even" I'll take a look at the PEP. Thanks. -- Michael F. Stemper This email is to be read by its intended recipient only. Any other party reading is required by the EULA to send me $500.00. -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On 22/04/2022 21.58, Avi Gross wrote: Python does have a concept of "truthy" that includes meaning for not just the standard Booleans but for 0 and non-zero and the empty string and many more odd things such as an object that defines __bool__ (). But saying it returns a Boolean True/False valuesounds direct and simple and informative enough if that is True. What bothers me is the assumption that anyone knows not so muchjust group theory but what the argument to the function looks like as a Python object of some kind. Does the function accept only some permutation object managed by a specific module? Will it accept some alternate representation such as a list structure or other iterator? That's a fair point. However, this function will be the 22nd one in a module for dealing with permutations and groups of permutations. The module has a lengthy docstring explaining the several ways provided to specify a permutation. That way, the same information doesn't need to be written twenty-plus times. Obviously deeper details would normally be in a manual page or other documentation but as "permutations" are likely not to be what most people think about before breakfast, or even after, odd as that may seem, ... I see what you did there :-> -- Michael F. Stemper Psalm 94:3-6 -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
We know some people using "professional" language make things shorteror talk from a point of view different than others and often in otherwise incomprehensible jargon. If a programmer is taking about the algorithm that a function implements, then, yes, they may write "scan" and "return". But if they realize the darn documentation is for PEOPLE asking how to use the darn thing, and want to write in more informal and understandable English, I think it makes more sense to say what the function does as in "scans" and importantly what it "returns" to the user as a result. So if you are taking a programming course and the instructor or textbook is giving imperitave commands, they may well tell youto scan something then calculate something and use a return statement a certain way. I can read many ways and am not particularly bothered by either style but when documenting what is, I prefer proper English (or any otherlanguage) in communicating what it does for them. As with many such things, if you work for a company or with groups of others, it is wise to find out what is expected and do the same as much as reasonable. -Original Message- From: MRAB To: python-list@python.org Sent: Fri, Apr 22, 2022 8:57 pm Subject: Re: Style for docstring On 2022-04-23 00:25, Rob Cliffe via Python-list wrote: > I don't use docstrings much; instead I put a line or two of comments > after the `def ` line. > But my practice in such situations is as per the OP's 3rd suggestion, e.g. > # Returns True if . > I'm curious as to why so many people prefer "Return" to "Returns". > Checking out help() on a few functions in the stdlib, they all used > "Return" or a grammatical equivalent, so this does seem to be a Python > cultural thing. But why? To me, "Returns" begins a description as to > what the function does, whereas "Return" is an imperative. But who is > it addresed to? Is a function considered to be a sentient entity that > can respond to a command? Is it an invocation to the lines of code > following the docstring: "Do this!" Might not the programmer mistakenly > think (if only for a moment) that the imperative is addressed to him? Maybe it's because the function name is often also an imperative, e.g.: >>> import re >>> help(re.search) Help on function search in module re: search(pattern, string, flags=0) Scan through string looking for a match to the pattern, returning a Match object, or None if no match was found. Note "Scan", not "scans". I was going to use 'print' as the example: >>> help(print) Help on built-in function print in module builtins: print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream. but it says "Prints", not "Print"... -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
Python does have a concept of "truthy" that includes meaning for not just the standard Booleans but for 0 and non-zero and the empty string and many more odd things such as an object that defines __bool__ (). But saying it returns a Boolean True/False valuesounds direct and simple and informative enough if that is True. What bothers me is the assumption that anyone knows not so muchjust group theory but what the argument to the function looks like as a Python object of some kind. Does the function accept only some permutation object managed by a specific module? Will it accept some alternate representation such as a list structure or other iterator? Obviously deeper details would normally be in a manual page or other documentation but as "permutations" are likely not to be what most people think about before breakfast, or even after, odd as that may seem, ... And, yes, I know what it means and some users will too. But as all permutations must be even or odd, errors thrown might be based on whether the data structure has valid contents or is so complex that it uses up all system resources, I would think. So the docstring could be fairly short and something like: Given a permutation in Returns the Boolean value True if it is graded as or False if or an exception if the argument is not valid. As noted by others, Many things can be returned including multiple values where perhaps the second one tells if there was an error but thatthe user can ignore or not even catch. -Original Message- From: Chris Angelico To: python-list@python.org Sent: Fri, Apr 22, 2022 6:33 pm Subject: Re: Style for docstring On Sat, 23 Apr 2022 at 08:24, <2qdxy4rzwzuui...@potatochowder.com> wrote: > > On 2022-04-22 at 15:35:15 -0500, > "Michael F. Stemper" wrote: > > > On 22/04/2022 14.59, Chris Angelico wrote: > > > On Sat, 23 Apr 2022 at 05:56, Michael F. Stemper > > > wrote: > > > > > > > > I'm writing a function that is nearly self-documenting by its name, > > > > but still want to give it a docstring. Which of these would be > > > > best from a stylistic point of view: > > > > > > > > > > > > Tells caller whether or not a permutation is even. > > > > > > > > Determines if a permutation is even. (Alternative is that it's odd.) > > > > > > > > Returns True if permutation is even, False if it is odd. > > > > > > > > > > I'd go with the third one, but "Return" rather than "Returns". Or > > > possibly "Test whether a permutation is even". > > > > "So let it be written. So let it be done." > > "Test whether a permutation is even," while technically factual, leaves > the reader to wonder what form the result takes, and what happens to > that result. While it's definitely possible to have other results and other ways to deliver them, the return of a boolean would be the most obvious default. > Do you want callers of the function also to assume that True means that > the permutation is even? There are other reasonable strategies, such as > an enumerated type (whose items are Even, Odd, and FileNotFound), or > throwing an exception if the permutation is odd. I'm assuming that the function is called something like "is_even()" and that it either is a method on a permutation object, or its parameters make it very clear what the permutation is. If it returns an enumeration, I would say that in the docstring. If the docstring doesn't say, I would assume it returns True or False. > I prefer the "return" (rather than "returns") version of the third > option. Assuming that the programmers are familiar with the domain, the > other two leave out important information. Core Python methods and functions seem to prefer either "Return ..." or "Verb the thing" where the result is implicit (eg str.zfill.__doc__ which says "Pad a numeric string..."). Both are used extensively. Neither form leaves out anything that wouldn't be the obvious default. We don't need to say "Figures out algorithmically whether the permutation is even. If it is, will return True; if it isn't, will return False; if something goes wrong, will raise an exception". This is Python; we know that if something goes wrong, an exception is raised. (Though it can help to say WHICH exception will be raised under WHAT circumstances). Some things are obvious. ChrisA -- https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On 2022-04-23 00:25, Rob Cliffe via Python-list wrote: I don't use docstrings much; instead I put a line or two of comments after the `def ` line. But my practice in such situations is as per the OP's 3rd suggestion, e.g. # Returns True if . I'm curious as to why so many people prefer "Return" to "Returns". Checking out help() on a few functions in the stdlib, they all used "Return" or a grammatical equivalent, so this does seem to be a Python cultural thing. But why? To me, "Returns" begins a description as to what the function does, whereas "Return" is an imperative. But who is it addresed to? Is a function considered to be a sentient entity that can respond to a command? Is it an invocation to the lines of code following the docstring: "Do this!" Might not the programmer mistakenly think (if only for a moment) that the imperative is addressed to him? Maybe it's because the function name is often also an imperative, e.g.: >>> import re >>> help(re.search) Help on function search in module re: search(pattern, string, flags=0) Scan through string looking for a match to the pattern, returning a Match object, or None if no match was found. Note "Scan", not "scans". I was going to use 'print' as the example: >>> help(print) Help on built-in function print in module builtins: print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream. but it says "Prints", not "Print"... -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On 22Apr2022 17:22, Dan Sommers <2qdxy4rzwzuui...@potatochowder.com> wrote: >"Test whether a permutation is even," while technically factual, leaves >the reader to wonder what form the result takes, and what happens to >that result. Yes, we'd all like to think that programmers are smart >enough to *assume* that the function returns the result of the test. >I've also seen functions that perform tests and then print the results >out, or write them to a database, or simply execute the tests for their >side effects (or leave it up to the individual tests to do something >with the result). Yeah, this. I've got lots of "test and return a Boolean" functions named "is_something" and some "test and raise value error if bad" functions named "validate_something". Those latter are so that I can concisely write stuff like: def foo(bah): validate_bahlike(bah) ... do stuff with bah ... to get a sensible ValueError from foo() if bah is invalid. (And validate_something() often calls is_something() when I want both flavors depending on circumstance.) So I also like option 3, though I also usually write it imperatively: Return `True` if `permutation` is even, `False` otherwise. I'm in two minds about "otherwise" rather than being explicit about the dual of the test. Usually "otherwise" is my choice, but I can imagine being more explicit if there were some third (probably invalid) input choice. "Otherwise" also works well when there are a few valid choices: Return `True` if the weekday is Wednesday or the moon is full, `False` otherwise. Cheers Cameron Simpson -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On Sat, 23 Apr 2022 at 09:31, Rob Cliffe via Python-list wrote: > > I don't use docstrings much; instead I put a line or two of comments > after the `def ` line. > But my practice in such situations is as per the OP's 3rd suggestion, e.g. > # Returns True if . The point of docstrings is that they can be read by various tools. Otherwise, they are every bit as good as comments. > I'm curious as to why so many people prefer "Return" to "Returns". > Checking out help() on a few functions in the stdlib, they all used > "Return" or a grammatical equivalent, so this does seem to be a Python > cultural thing. But why? To me, "Returns" begins a description as to > what the function does, whereas "Return" is an imperative. But who is > it addresed to? Is a function considered to be a sentient entity that > can respond to a command? Is it an invocation to the lines of code > following the docstring: "Do this!" Might not the programmer mistakenly > think (if only for a moment) that the imperative is addressed to him? That's a very broad convention; for instance, git commit messages are conventionally written imperatively, too. You can think of a commit message as "If applied, this patch will blah blah blah", and a docstring as "When called, this function will blah blah blah". Aside from the initial capital letter, an imperative sentence will nicely complete those descriptions. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
I don't use docstrings much; instead I put a line or two of comments after the `def ` line. But my practice in such situations is as per the OP's 3rd suggestion, e.g. # Returns True if . I'm curious as to why so many people prefer "Return" to "Returns". Checking out help() on a few functions in the stdlib, they all used "Return" or a grammatical equivalent, so this does seem to be a Python cultural thing. But why? To me, "Returns" begins a description as to what the function does, whereas "Return" is an imperative. But who is it addresed to? Is a function considered to be a sentient entity that can respond to a command? Is it an invocation to the lines of code following the docstring: "Do this!" Might not the programmer mistakenly think (if only for a moment) that the imperative is addressed to him? Best wishes Rob Cliffe -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On 2022-04-23 at 08:33:37 +1000, Chris Angelico wrote: > On Sat, 23 Apr 2022 at 08:24, <2qdxy4rzwzuui...@potatochowder.com> wrote: > > > > On 2022-04-22 at 15:35:15 -0500, > > "Michael F. Stemper" wrote: > > > > > On 22/04/2022 14.59, Chris Angelico wrote: > > > > On Sat, 23 Apr 2022 at 05:56, Michael F. Stemper > > > > wrote: > > > > > > > > > > I'm writing a function that is nearly self-documenting by its name, > > > > > but still want to give it a docstring. Which of these would be > > > > > best from a stylistic point of view: > > > > > > > > > > > > > > > Tells caller whether or not a permutation is even. > > > > > > > > > > Determines if a permutation is even. (Alternative is that it's > > > > > odd.) > > > > > > > > > > Returns True if permutation is even, False if it is odd. > > > > > > > > > > > > > > I'd go with the third one, but "Return" rather than "Returns". Or > > > > possibly "Test whether a permutation is even". > > > > > > "So let it be written. So let it be done." > > > > "Test whether a permutation is even," while technically factual, leaves > > the reader to wonder what form the result takes, and what happens to > > that result. > > While it's definitely possible to have other results and other ways to > deliver them, the return of a boolean would be the most obvious > default. Maybe, depending on the context and purpose of the application. > > Do you want callers of the function also to assume that True means that > > the permutation is even? There are other reasonable strategies, such as > > an enumerated type (whose items are Even, Odd, and FileNotFound), or > > throwing an exception if the permutation is odd. > > I'm assuming that the function is called something like "is_even()" > and that it either is a method on a permutation object, or its > parameters make it very clear what the permutation is. > > If it returns an enumeration, I would say that in the docstring. If > the docstring doesn't say, I would assume it returns True or False. I think we're agreeing, but the OP didn't provide that information. I've seen enough oddball (yes, that's my professional opinion :-)) APIs (and worked with enough programmers from enough backgrounds) to know that "most obvious default" is subjective. > > I prefer the "return" (rather than "returns") version of the third > > option. Assuming that the programmers are familiar with the domain, > > the other two leave out important information. [...] > We don't need to say "Figures out algorithmically whether the > permutation is even. If it is, will return True; if it isn't, will > return False; if something goes wrong, will raise an exception". This > is Python; we know that if something goes wrong, an exception is > raised. (Though it can help to say WHICH exception will be raised > under WHAT circumstances). Some things are obvious. No, we don't need to say it that way. I believe that we do need to say what the function returns under what circumstances. If, in fact, the function in question is named is_permutation_even, then it *is* as simple as the OP's third option, but not simpler. -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On Sat, 23 Apr 2022 at 08:24, <2qdxy4rzwzuui...@potatochowder.com> wrote: > > On 2022-04-22 at 15:35:15 -0500, > "Michael F. Stemper" wrote: > > > On 22/04/2022 14.59, Chris Angelico wrote: > > > On Sat, 23 Apr 2022 at 05:56, Michael F. Stemper > > > wrote: > > > > > > > > I'm writing a function that is nearly self-documenting by its name, > > > > but still want to give it a docstring. Which of these would be > > > > best from a stylistic point of view: > > > > > > > > > > > > Tells caller whether or not a permutation is even. > > > > > > > > Determines if a permutation is even. (Alternative is that it's odd.) > > > > > > > > Returns True if permutation is even, False if it is odd. > > > > > > > > > > I'd go with the third one, but "Return" rather than "Returns". Or > > > possibly "Test whether a permutation is even". > > > > "So let it be written. So let it be done." > > "Test whether a permutation is even," while technically factual, leaves > the reader to wonder what form the result takes, and what happens to > that result. While it's definitely possible to have other results and other ways to deliver them, the return of a boolean would be the most obvious default. > Do you want callers of the function also to assume that True means that > the permutation is even? There are other reasonable strategies, such as > an enumerated type (whose items are Even, Odd, and FileNotFound), or > throwing an exception if the permutation is odd. I'm assuming that the function is called something like "is_even()" and that it either is a method on a permutation object, or its parameters make it very clear what the permutation is. If it returns an enumeration, I would say that in the docstring. If the docstring doesn't say, I would assume it returns True or False. > I prefer the "return" (rather than "returns") version of the third > option. Assuming that the programmers are familiar with the domain, the > other two leave out important information. Core Python methods and functions seem to prefer either "Return ..." or "Verb the thing" where the result is implicit (eg str.zfill.__doc__ which says "Pad a numeric string..."). Both are used extensively. Neither form leaves out anything that wouldn't be the obvious default. We don't need to say "Figures out algorithmically whether the permutation is even. If it is, will return True; if it isn't, will return False; if something goes wrong, will raise an exception". This is Python; we know that if something goes wrong, an exception is raised. (Though it can help to say WHICH exception will be raised under WHAT circumstances). Some things are obvious. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On 2022-04-22 at 15:35:15 -0500, "Michael F. Stemper" wrote: > On 22/04/2022 14.59, Chris Angelico wrote: > > On Sat, 23 Apr 2022 at 05:56, Michael F. Stemper > > wrote: > > > > > > I'm writing a function that is nearly self-documenting by its name, > > > but still want to give it a docstring. Which of these would be > > > best from a stylistic point of view: > > > > > > > > > Tells caller whether or not a permutation is even. > > > > > > Determines if a permutation is even. (Alternative is that it's odd.) > > > > > > Returns True if permutation is even, False if it is odd. > > > > > > I'd go with the third one, but "Return" rather than "Returns". Or > > possibly "Test whether a permutation is even". > > "So let it be written. So let it be done." "Test whether a permutation is even," while technically factual, leaves the reader to wonder what form the result takes, and what happens to that result. Yes, we'd all like to think that programmers are smart enough to *assume* that the function returns the result of the test. I've also seen functions that perform tests and then print the results out, or write them to a database, or simply execute the tests for their side effects (or leave it up to the individual tests to do something with the result). Do you want callers of the function also to assume that True means that the permutation is even? There are other reasonable strategies, such as an enumerated type (whose items are Even, Odd, and FileNotFound), or throwing an exception if the permutation is odd. I prefer the "return" (rather than "returns") version of the third option. Assuming that the programmers are familiar with the domain, the other two leave out important information. -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On Fri, 22 Apr 2022 14:36:27 -0500, Michael F. Stemper wrote: > I'm writing a function that is nearly self-documenting by its name, > but still want to give it a docstring. Which of these would be best from > a stylistic point of view: > > >Tells caller whether or not a permutation is even. > >Determines if a permutation is even. (Alternative is that it's odd.) > >Returns True if permutation is even, False if it is odd. > > > (Before somebody suggests it, I'm not going to put six weeks' worth of a > course in group theory in there to help somebody who doesn't know what > those standard terms mean.) four guidance I would sugest Pep257 as a start point which would suggest "Return True if permutation is even" -- I think my career is ruined! -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On 22/04/2022 14.59, Chris Angelico wrote: On Sat, 23 Apr 2022 at 05:56, Michael F. Stemper wrote: I'm writing a function that is nearly self-documenting by its name, but still want to give it a docstring. Which of these would be best from a stylistic point of view: Tells caller whether or not a permutation is even. Determines if a permutation is even. (Alternative is that it's odd.) Returns True if permutation is even, False if it is odd. I'd go with the third one, but "Return" rather than "Returns". Or possibly "Test whether a permutation is even". "So let it be written. So let it be done." That's just one opinion though, others may disagree :) Two for two. Thanks. -- Michael F. Stemper Always remember that you are unique. Just like everyone else. -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On 4/22/22 12:36, Michael F. Stemper wrote: Tells caller whether or not a permutation is even. Determines if a permutation is even. (Alternative is that it's odd.) Returns True if permutation is even, False if it is odd. Third option. -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: Style for docstring
On Sat, 23 Apr 2022 at 05:56, Michael F. Stemper wrote: > > I'm writing a function that is nearly self-documenting by its name, > but still want to give it a docstring. Which of these would be > best from a stylistic point of view: > > >Tells caller whether or not a permutation is even. > >Determines if a permutation is even. (Alternative is that it's odd.) > >Returns True if permutation is even, False if it is odd. > > > (Before somebody suggests it, I'm not going to put six weeks' worth > of a course in group theory in there to help somebody who doesn't > know what those standard terms mean.) > I'd go with the third one, but "Return" rather than "Returns". Or possibly "Test whether a permutation is even". That's just one opinion though, others may disagree :) ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Style for docstring
I'm writing a function that is nearly self-documenting by its name, but still want to give it a docstring. Which of these would be best from a stylistic point of view: Tells caller whether or not a permutation is even. Determines if a permutation is even. (Alternative is that it's odd.) Returns True if permutation is even, False if it is odd. (Before somebody suggests it, I'm not going to put six weeks' worth of a course in group theory in there to help somebody who doesn't know what those standard terms mean.) -- Michael F. Stemper 87.3% of all statistics are made up by the person giving them. -- https://mail.python.org/mailman/listinfo/python-list