[Python-ideas] Re: Auto assignment of attributes
On 4/28/22 21:46, Christopher Barker wrote: > One thing you can say about dataclasses is that they provide a way to handle all parameters, mutable and immutable. Really? I did not know that. Interesting. Definitely an issue of dataclasses being special, though, and not attributable to the syntax used to make a dataclass. -- ~Ethan~ ___ 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/76GFMSU7OVG3GMFXD52TJFSPG47N2QLR/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Auto assignment of attributes
On Thu, Apr 28, 2022 at 4:15 PM Ethan Furman wrote: > > NOTE: another key question for this proposal is how you would handle > mutable defaults -- anything > > special, or "don't do that"? > > Why should they be handled at all? If the programmer writes > > def __init__(a, @b, @c=[]): > pass > > then all instances that didn't have `c` given will share the same list -- > just like if the code was: > > def __init__(a, b, c=[]): > self.b = b > self.c = c > so the answer is "don't do that" (unless, in the rare case, that's what you actually want). The purpose of the syntax is to automatically save arguments to same-named > attributes, not to perform any other magic. > If the programmer writes def __init__(a, @b, @c=[]): pass sure but that's the coon case -- more common would be: def __init__(a, @b, c=None): handle_a if c is None: c = [] or some such. so without "any other magic", then we have a less useful proposal. One thing you can say about dataclasses is that they provide a way to handle all parameters, mutable and immutable. Anyway, I just thought it should be clearly said. -CHB -- Christopher Barker, PhD (Chris) Python Language Consulting - Teaching - Scientific Software Development - Desktop GUI and Web Development - wxPython, numpy, scipy, Cython ___ 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/HYRQPWXMPJ727FQWEJ4GY2SMUEABKEGW/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Auto assignment of attributes
On 4/23/22 12:11, Christopher Barker wrote: > NOTE: another key question for this proposal is how you would handle mutable defaults -- anything > special, or "don't do that"? Why should they be handled at all? If the programmer writes def __init__(a, @b, @c=[]): pass then all instances that didn't have `c` given will share the same list -- just like if the code was: def __init__(a, b, c=[]): self.b = b self.c = c The purpose of the syntax is to automatically save arguments to same-named attributes, not to perform any other magic. -- ~Ethan~ ___ 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/HXQ6K6RF5AZ7XLNWRXGSNKN4KOIYZZ7E/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Auto assignment of attributes
On 4/21/22 15:12, Joao S. O. Bueno wrote: > On Thu, Apr 21, 2022 at 5:17 PM Pablo Alcain wrote: >> I think that discussion can probably belong to a specific thread with the proposal with >> your questions summary there so everyone can contribute to the implementation that, clearly, >> has some interesting points that it would be better if we could discuss in detail. > > Sorry. It looks like you are claiming... the _thread_ , is that it? > > Very well. The thread may be all yours! Well, Pablo is the OP of this thread, so that seems entirely reasonable. ;-) -- ~Ethan~ ___ 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/TF2JHUEUDYLEZ33PPWCTT3VPKD5UNPQO/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Delete dictionary entry if key exists using -= operator via __isub__()
Agree — it is perhaps a bit strange to use an operator for something other than dictionary-to-dictionary operations. And, yes, benchmarking is the only way to know—but I think your hypothesis is a good one. ___ 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/LFDLZRTYDMETNHEW76QLEWUZPINSXU3P/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Delete dictionary entry if key exists using -= operator via __isub__()
> Can you give an example of real code that does this? In general, parsing JSON data and normalizing it. The existing architecture has microservices consuming PubSub messages for which the data-payload is JSON. In some cases, deleting dictionary keys is convenient (as opposed to, say, building a new dict and dumping it), as a way to prepare it for the downstream consumer. I should say, there is no inherent need for a new way to delete a dictionary entry. This was merely an "idea" to a list of "ideas"! I appreciate the fair criticism and consideration, along with that of Antoine and Chris. I agree with you that there is probably no need for a fourth solution. ___ 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/LB2ZNKSQLGUYN5MRQRSGLBUJ56QCSW2Y/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Delete dictionary entry if key exists using -= operator via __isub__()
The original idea was actually not to write function, but thank you for telling me that I am welcome to do so—that is very kind of you and, indeed, welcoming. I don't know whether to consider it an improvement. It is a nice function. ___ 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/TPKAFD36MXZLUVZOK35O4R2YCXL7PUGS/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Auto assignment of attributes
On 4/21/22 10:29, Joao S. O. Bueno wrote: > I take the freedom to interpret 'no news == good news' on this thread - > nominally that there are no major disagreements that a decorator > to auto-commit `__init__` atributes to the instance could be a nice addition > to the stdlib. I am strongly against using a decorator for this purpose. It would only be useful when *all* the arguments are saved as-is; in those cases where only *some* of them are, it either wouldn't work at all or would need to retype the names which would eliminate all benefits of using a decorator. -- ~Ethan~ ___ 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/7XRIXX2XP7KXAFV4XU4GQTP5YLERY7EH/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Delete dictionary entry if key exists using -= operator via __isub__()
On Fri, 29 Apr 2022 at 07:44, Steven D'Aprano wrote: > > Especially not when that solution is easily mistaken for something else: > > d -= 1 # Are we subtracting 1, or deleting key 1? > IMO it would make more sense to spell it as subtraction of two similar types: d -= {1} # supporting sets would be nice d -= {1: ...} If subtraction on dicts is ever supported, I doubt it would allow subtracting one key from the dict - it would make much more sense to subtract another dictionary. But for the single elimination case, pop() is perfect for the job. Oh, and since we're making evidence-free predictions about performance, I'm going to put in my guesses too: "if key in mydict: del mydict[key]" will be slower than pop(), and the try/except could be about comparable, but could be slightly slower or faster. (If we were placing bets, I'd bet on pop() being the fastest of the three overall, but that's a weaker prediction.) Now we just need someone to make the ultimate benchmark so we can find out :) ChrisA ___ 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/4R6NY4KLQ6JEHCR7MFNABCBDR7PE4M62/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Delete dictionary entry if key exists using -= operator via __isub__()
On Thu, Apr 28, 2022 at 01:18:09AM -, zmvic...@gmail.com wrote: > *Background* > It is frequently desirable to delete a dictionary entry if the key > exists. Frequently? I don't think I've ever needed to do that. Can you give an example of real code that does this? > It is necessary to check that the key exists or, > alternatively, handle a KeyError: for, where `d` is a `dict`, and `k` > is a valid hashable key, `del d[k]` raises KeyError if `k` does not > exist. The simplest one-liner to delete a key if and only if it exists is with the `pop` method: mydict.pop(key, None) # Ignore the return result. That may not be the most efficient way. I expect that the most efficient way will depend on whether the key is more likely to exist or not: # Not benchmarked, so take my predictions with a pinch of salt. # Probably fastest if the key is usually present. try: del mydict[key] except KeyError: pass # Probably fastest if the key is usually absent. if key in mydict: del mydict[key] So we already have three ways to delete only an existing key from a dict, "optimised" (in some sense) for three scenarios: - key expected to be present; - key expected to be absent; - for convenience (one-liner). With three existing solutions to this problem, it is unlikely that a fourth solution will be blessed by building it into the dict type itself. (Although of course you can add it to your own subclasses.) Especially not when that solution is easily mistaken for something else: d -= 1 # Are we subtracting 1, or deleting key 1? Alone, that is not a fatal problem, but given that there are three other satisfactory solutions to the task of deleting an existing key, even minor or trivial problems push the cost:benefit ratio into the negative. By the way: > class DemoDict(dict): > def __init__(self, obj): > super().__init__(obj) If the only purpose of a method is to call super and inherit from its parent class(es), as in the above, then you don't need to define the method at all. Just leave it out, and the parent's `__init__` will be called. -- Steve ___ 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/JUPJN2NNEANAOMSMFHTNNFSBRIM2INW7/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Delete dictionary entry if key exists using -= operator via __isub__()
On Fri, 29 Apr 2022 at 07:15, Zach Victor wrote: > > I agree that "implicit" does not mean "code that one dislikes." The intent is > "delete entry if key exists." Is that implicit or explicit? > "[R]emove specified key and return the corresponding value", with a default if there isn't one. Is that explicit enough? > Positing a default value to discard it as a return value is, arguably, what > makes the intent of that construction implicit. I say "arguably," because > that is the material that is under consideration (not whether one likes it). > You're welcome to create your own function to wrap it up, if you really think that that's a problem: def discard(dict, key): _ignoreme = dict.pop(key, None) del _ignoreme # because it's not explicit enough to just abandon an object Is that an improvement? ChrisA ___ 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/SLGBV5OMN73WOLCRPYSL7DOZQBEZW2E3/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Delete dictionary entry if key exists using -= operator via __isub__()
I agree that "implicit" does not mean "code that one dislikes." The intent is "delete entry if key exists." Is that implicit or explicit? Positing a default value to discard it as a return value is, arguably, what makes the intent of that construction implicit. I say "arguably," because that is the material that is under consideration (not whether one likes it). ___ 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/QUUSEVRE3NKLLRATFXOZAKYXZPGLGPLZ/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Delete dictionary entry if key exists using -= operator via __isub__()
On Fri, 29 Apr 2022 at 04:03, Zach Victor wrote: > Where does this land with PEP 20? I think the use of pop() as you suggest > lands on the implicit side of things and is not as readable: the reader has > to ask, "what are we doing with the default value? Oh. Nothing. It's to > delete a dict entry." However, pop() with the default value of None is > practical, and practicality does beat purity. > "Implicit" does not mean "code that I dislike". The pop method is exactly what it appears to be: a way to remove something, with either an error or a default if it's not found. It then returns the thing. Ignoring a function's return value is perfectly normal. There are all manner of functions which you use all the time, and it's not a problem to have them return something you usually don't care about (like f.write() returning how much it wrote). ChrisA ___ 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/AF4AE2OLULG3VHZSN47U73AFGA73JE5A/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Delete dictionary entry if key exists using -= operator via __isub__()
Using `dct -= key` is WAAAYY too cryptic. A method would be okay, but since that is just `dct.pop(key, None)` without the second argument, it's not worth the trouble. -1 On Thu, Apr 28, 2022, 12:03 PM Zach Victor wrote: > Good points, Antoine! > > The intent is to mutate the dictionary with no side effects if a key > exists — and without the extra code that comes along with a control > structure, a try except, or positing a None to throw away. > > For me, pop() says "give me something." Since the intent is to mutate the > dictionary only and not "get something," I'd prefer (i) not to use a > function that returns a value and (ii) not to specify a return value None > just so that it can be thrown away. Perhaps if pop()'s default return value > were None—as it is with, say, get()—I would use pop() as you describe. But > pop() doesn't have a default value unless you give it one, and pop() always > returns a value. > > Where does this land with PEP 20? I think the use of pop() as you suggest > lands on the implicit side of things and is not as readable: the reader has > to ask, "what are we doing with the default value? Oh. Nothing. It's to > delete a dict entry." However, pop() with the default value of None is > practical, and practicality does beat purity. > > I agree that operator overloading needs to be consistent and easy to > understand, and in that regard -= with the dict key probably does not > withstand the PEP 20 tests. Furthermore, in support of your point, the > language has moved in the direction of set operations between dicts using > operators: for example, + for union of dicts. To satisfy set- and key-based > operations, one could overload the augmented arithmetic assignment > operators so that -= with a string would delete the entry with a matching > key, while -= with a dict would delete the entry with a matching key and > value. Again, that may be too recherché or hard-to-explain (cf PEP 20). > > Perhaps, then, it would be best to leave dict alone and just overload > operators in subclasses for specific uses! > ___ > 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/ICUUGL7DABI3VTL4GDSNVOM7D3HEO467/ > Code of Conduct: http://python.org/psf/codeofconduct/ > ___ 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/ZKRCW2ZPKKZW6TLV7SHLK4CJRJPBDB3N/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Delete dictionary entry if key exists using -= operator via __isub__()
Good points, Antoine! The intent is to mutate the dictionary with no side effects if a key exists — and without the extra code that comes along with a control structure, a try except, or positing a None to throw away. For me, pop() says "give me something." Since the intent is to mutate the dictionary only and not "get something," I'd prefer (i) not to use a function that returns a value and (ii) not to specify a return value None just so that it can be thrown away. Perhaps if pop()'s default return value were None—as it is with, say, get()—I would use pop() as you describe. But pop() doesn't have a default value unless you give it one, and pop() always returns a value. Where does this land with PEP 20? I think the use of pop() as you suggest lands on the implicit side of things and is not as readable: the reader has to ask, "what are we doing with the default value? Oh. Nothing. It's to delete a dict entry." However, pop() with the default value of None is practical, and practicality does beat purity. I agree that operator overloading needs to be consistent and easy to understand, and in that regard -= with the dict key probably does not withstand the PEP 20 tests. Furthermore, in support of your point, the language has moved in the direction of set operations between dicts using operators: for example, + for union of dicts. To satisfy set- and key-based operations, one could overload the augmented arithmetic assignment operators so that -= with a string would delete the entry with a matching key, while -= with a dict would delete the entry with a matching key and value. Again, that may be too recherché or hard-to-explain (cf PEP 20). Perhaps, then, it would be best to leave dict alone and just overload operators in subclasses for specific uses! ___ 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/ICUUGL7DABI3VTL4GDSNVOM7D3HEO467/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Delete dictionary entry if key exists using -= operator via __isub__()
You could use the pop method on dictionary (with a default value of None for example) to remove the key only if it exists. The method returns the value associated with this key but you can ignore it. I'm not sure the __isub__ implementation would be easy to understand as it's weird to make a subtraction between a dict and a str. Even sets only support subtraction between sets. (Also you have Counter objects from collections module that implement a kind of subtraction between dicts) Le jeu. 28 avr. 2022 à 15:19, a écrit : > *Background* > It is frequently desirable to delete a dictionary entry if the key exists. > It is necessary to check that the key exists or, alternatively, handle a > KeyError: for, where `d` is a `dict`, and `k` is a valid hashable key, `del > d[k]` raises KeyError if `k` does not exist. > > Example: > ``` > if k in d: > del d[k] > ``` > > *Idea* > Use the `-=` operator with the key as the right operand to delete a > dictionary if the key exists. > > *Demonstration-of-Concept* > ``` > class DemoDict(dict): > def __init__(self, obj): > super().__init__(obj) > > def __isub__(self, other): > if other in self: > del self[other] > return self > > > if __name__ == '__main__': > given = {'a': 1, 'b': 2, 'c': 3, 'd': 4} > demo = DemoDict(given) > demo -= 'c' > assert(demo == {'a': 1, 'b': 2, 'd': 4}) > ``` > ___ > 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/BBFALX57PJI4ALF4O6YGYMHMLNL4U4YI/ > Code of Conduct: http://python.org/psf/codeofconduct/ > -- Antoine Rozo ___ 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/NUAZIYUFTGMIWIBORQQOKEO63HWK2XRW/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Delete dictionary entry if key exists using -= operator via __isub__()
*Background* It is frequently desirable to delete a dictionary entry if the key exists. It is necessary to check that the key exists or, alternatively, handle a KeyError: for, where `d` is a `dict`, and `k` is a valid hashable key, `del d[k]` raises KeyError if `k` does not exist. Example: ``` if k in d: del d[k] ``` *Idea* Use the `-=` operator with the key as the right operand to delete a dictionary if the key exists. *Demonstration-of-Concept* ``` class DemoDict(dict): def __init__(self, obj): super().__init__(obj) def __isub__(self, other): if other in self: del self[other] return self if __name__ == '__main__': given = {'a': 1, 'b': 2, 'c': 3, 'd': 4} demo = DemoDict(given) demo -= 'c' assert(demo == {'a': 1, 'b': 2, 'd': 4}) ``` ___ 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/BBFALX57PJI4ALF4O6YGYMHMLNL4U4YI/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Enum should use __class_getitem__
Although ENUMs are already complicated enough, this proposals frees up messing with the EnumMeta metaclass in some cases - it makes sense. I've subclassed EnumMeta once for adding some feature in a project, and it never feels the "quite right" thing to do. On Tue, Apr 26, 2022 at 6:12 PM Stefan Nelson-Lindall < stefan.nelsonlind...@gmail.com> wrote: > EnumMeta implements its own __getitem__ function which doesn't respect > __class_getitem__. Now that __class_getitem__ exists, this behavior feels > unintuitive. For instance > > ``` > class Directions(enum.Enum): > LEFT = "LEFT" > RIGHT = "RIGHT" > > def __class_getitem__(cls, name): > return super().__class_getitem__(name.upper()) > > # fails with KeyError -- __class_getitem__ never called > assert Directions["left"] == Directions["LEFT"] == Directions.LEFT > ``` > > doesn't work, and the only way to implement this behavior is something like > > ``` > class MyEnumMeta(enum.EnumMeta): > def __getitem__(cls, name): > return cls.__class_getitem__(name) > > class MyEnum(enum.Enum, metaclass=MyEnumMeta): > def __class_getitem__(cls, name): > return cls._member_map_[name] > > class Directions(MyEnum): ... > ``` > > there might be some compatibility issues with code written between 3.4 and > 3.11, but not supporting __class_getitem__ feels like it violates the > principle of least surprise with the more recent data models. > ___ > 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/4VURZ4ZXPZRQ726KZH5DAOI47XXUKBI2/ > Code of Conduct: http://python.org/psf/codeofconduct/ > ___ 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/NSN667S6QVHSV74XSZ6LFT5JNIRHFYFO/ Code of Conduct: http://python.org/psf/codeofconduct/