[Python-ideas] Re: An alternative way of defining properties (warning: contains creative abuse of the class statement)
02.07.20 13:26, Greg Ewing пише: On 2/07/20 8:04 pm, Serhiy Storchaka wrote: It has a problem with pickling (it is solvable). Can you elaborate? The end result is a property object just the same as you would get from using @property or calling property directly. I don't see how it can have any pickling problems beyond what properties already have. You are right since property objects currently are not pickleable by default. But it is possible to implement pickling support for property objects which will fail with your example (and I think third-party libraries do it). The difference is that full qualified names of getter and setter differ from the full qualified name of the property. It is solvable, but it may require more complex code. The larger problem is with using private (double underscored) variables and super(). I don't know what you're talking about here. I didn't use any double-underscore names in my example. Then try to use them. It would not work. class Test2: def __init__(self): self.__foo = 1 class foo(metaclass = Property): def get(self): return self.__foo Test2().foo class Test3Base: @property def foo(self): return 1 class Test3(Test3Base): class foo(metaclass = Property): def get(self): return super().foo + 1 Test3().foo ___ 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/NGYNDVVQECY2KI6LVC7DUAHJ2IYQKT54/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Add __eq__ to colletions.abc.Sequence ?
On Wed, Jul 1, 2020, at 08:23, Joao S. O. Bueno wrote: > collections.mixins.SlicedSequence that would override `__delitem__`, > `__setitem__` and `__getitem__` and > handle slices could pair up with the "ComparableSequence" - people > could use these "a la carte", and > no backwards compatibility would be hurt. This one raises the question of where you put the single-item accessors. And sliced __delitem__ may be difficult to implement efficiently without knowing the internals of the sequence type. ___ 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/7HLNBVJSVA5S5EDOK7LFCQNWUMOTJXLS/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Best approach for opaque PyObject
On Thu, Jul 2, 2020, at 20:39, William Pickard wrote: > I do have a plan to solve that problem, it involves adding about 24 > more bytes to PyTypeObject, but it would allow Python to track offset > from base object, total object size and best alignment value. I'm not sure I'm following how that would help, but it sounds like you're saying that pointers to extension-defined data structure would not be PyTypeObject pointers, and vice versa? At least not without interconversion using this offset, which adds more overhead. ___ 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/KLN5GG26WXWUTJ7R3RT2XYNY545QE4PB/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Else assert statement
An alternative way of doing what you need that doesn't add any syntax, is more readable, runs faster, scales better and has long been used as the reason that python doesn't need a case statement would be: # Dictionary of which actions to take for foo foo_action_dict = { 'a':a, 'b':b, 'c':c, } def foo_default_handler(): """ Handler for remaining cases of foo """ print("Input value must be one of", foo_action_dict.keys()) # Call the appropriate action for foo: action_dict.get(foo, foo_default_handler)() [Steve Barnes] ___ 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/A52OOY52V3IHGRNFGZPEENHW42ICCU6V/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Best approach for opaque PyObject
I do have a plan to solve that problem, it involves adding about 24 more bytes to PyTypeObject, but it would allow Python to track offset from base object, total object size and best alignment value. ___ 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/NBNUBJOF4YD3535AW2LGGGPK7S3GPPDW/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] [Suspected Spam]Re: Access (ordered) dict by index; insert slice
Stestagg writes: > Having said that, it's a 70-line change, so fixing that up should be > trivial once the change has some agreement behind it. I still don't see a plausible use case that isn't well served by list(view). The OP's "addressing database columns" is superficially plausible, but the indexing mapping is *intended* to be unstable (inserting columns at positions). So the only operation where you can actually use an index would be something like i = db.columns.index("Name") db.columns.insert(i + 1, Address, address_data) because now all indicies > i have been invalidated. But I can't see how having a dict to map names to indicies and simply rebuilding the dict on every change to the list of names is going to be a problem for this application. And of course you'd need to add index and insert methods to support that: things are getting complicated. You say you don't want to copy data out of giant structures. That's a good idea, and of course very much a motivation for the view concept itself. But since views are immutable unless you change the underlying dict, many applications (sorting and creating heaps come to mind) are going to require copying the data. Many applications that don't will require a way to pick out a particular index, which you haven't provided. Yet others process the whole data, which can be iterated (and in particular functools.reduce works as expected). If you don't like the iteration order (eg, because you want an accurate sum() for floats), you need to copy the data (see "sorting and creating heaps"). So what are these use cases? Granted, my imagination may be insufficient, but so far, so are those of the proponents, who all write in terms of "convenience" and other real but very abstract values. On the downside, dicts may be the single most carefully optimized data type in Python, and that effort has clearly been repaid. But it also required a large change in the layout of the data structure. It seems unlikely that that would happen again, but genius is pretty unpredictable. Do we want to further constrain the implementation by requiring support for what seem to be marginally-useful operations? Regards, 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/5DUYVU2ABLYTNRQUH2RG3WTNVA5C7BAT/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: giving set.add a return value
Christopher Barker writes: > On Mon, Jun 29, 2020 at 1:53 AM Stephen J. Turnbull < > turnbull.stephen...@u.tsukuba.ac.jp> wrote: > > But if it turns out that somebody *wants* to check "2 is 2.0", > > this .add_unique can serve both purposes. > can it though? Yes. > (or should it?) YMMV, but I think that's not our call. This check *can* be done without this facility, but AFAICS it would be O(n) (iterate over the set, testing for equality, then testing for identity if found). Providing this function simply optimizes that to O(1). The argument against this isn't "should we distinguish int from float in principle", it's "should we bother with a status return at all" and "if we bother, why not KISS with a boolean return", don't you think? > -- the fact is that it was decided the 2 and 2.0 are equivalent as > members of a set (which makes great sense, there are they SAME > number, and the difference is an implementation detail), No, it's not just an implementation detail. If 2.0 can sneak into an integer set, so can Inf and Nan, but any integer calculation using members of that set will not be prepared for that. And it's possible that 2.001 can sneak in as well, changing an exact integer calculation into floating point calculation with rather different rules. This is the same kind of argument used to justify zip(strict=True). I.e, this only happens if there's a programmer error, and if it does, the feature helps to debug that error. > I've lost track, but the answer to > > a_set.add_unique(2) > should always be the same as > a_set.add_unique(2.0) > > for the same set. True. What about that? That's what makes it possible to tell whether you added the same object or merely an equal one. I don't have time to think carefully about it, but it now occurs to me to spell add_unique as "intern", as in the idiom x = a_set.intern(x) Of course we already have this for str, but only str, with sys.intern. It would likely be a rare use case compared to strings, but in theory any immutable could benefit from this. ___ 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/TIHXYHI5H7U5SITKIYGHINYDFTVGV2MB/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: What about having a .get(index, default) method for arrays like we have for dicts?
Alex Hall writes: > `dct.get('foo')?.get(0)?.get('bar')`. > > I would quite like to have PEP 505, but I don't know how to revive it. And > I'm not surprised that it's deferred, there's generally reluctance to add > new syntax, especially symbols. Bottom line: new use cases or modified semantics that are more attractive to people who don't sympathize with the "in NOSQL objects often aren't there" use case. Some handwavy discussion below. Note that Nick Coghlan in the PEP 622 thread over on python-dev is proposing a very different use for '?' which seems likely to conflict. It wouldn't rule out syntax, but definitely would make it more difficult to use '?' (though probably not syntactically impossible) for this purpose. > I haven't seen anyone in this thread suggesting any cost or > downside of adding the method, just people asking if it would be > useful. I feel like I answered that question pretty thoroughly, > then the thread went quiet. Unfortunately, the people whose answers you really want to hear don't hang out here much any more. Steven d'A has remarkably comprehensive knowledge, but he's not as good at channeling Guido on what isn't yet as he is at explaining what is already. Not sure where Andrew Barnert has got to recently, but put him and Steven together and you get the best of both that's available here. Greg Ewing is another valuable source, but his design instincts often are quite different from Guido's. Lots of good ideas and discussion from these developers, but add all that up and you don't get Guido or Barry or Nick. Not necessarily *worse*, but different, and if you can't show that some feature requires a horrible hack or inordinate amounts of hard-to-get-right trickery, being different from Guido still connotes being un-Pythonic, and that's hard to get around. (Don't let that stop you from arguing with Guido -- among his other remarkable characteristics, he's been known to change his mind and accept features he long opposed. :-) I don't suggest that you try to open up a thread on python-dev where the folks who dropped the acid in the Kool-Aid do show up frequently. All of the reasons you and others give for wanting this are well- known, and they just didn't do it. Until you've got a powerful new argument or different, more attractive semantics, you'll just get shooed back here. I can say that it's not just the high cost of a symbol that tabled that PEP. Chained accesses like "dct['foo'][0]['bar'] are just expressions, but among the old-timers there's a deep suspicion of the "fluent" style of programming, chaining method calls by returning self. This isn't the same thing, but "null coalescing" operators (I prefer "null propagating" but "coalescing" seems to be the preferred term among proponents) has something of the same flavor, albeit only for None. It necessarily privileges None[1], guaranteeing ambiguity of that value, especially in a context like parsing JSON, where JSON null is typically translated to Python None. There was also a concern that null coalescing encourages hard to debug, unmaintainable programming. I don't think anybody provided hard evidence on that count, but introducing an operator specifically to *postpone* detection of exceptional conditions just doesn't sit well with a lot of people. It confuses things that *should* be there but aren't, with things that *might* be there but aren't, and with None when it's actually there. Postponing error detection can be done with 'try', but try doesn't confuse those things.[2] The principle of "consenting adults" means that possibility of misuse won't kill an otherwise good idea, but the question "isn't there a more Pythonic, explicit semantics that doesn't allow errors to propagate?" is one way to get an idea tabled. Finally, once you compare null-coalescing operators with 'try', it's clear that 'try' is far more powerful as well as sufficient for this application, and it's just not clear that null-coalescing is sufficiently special a special case to deserve syntax. Don't @ me. That is, I don't have a horse in this race (except that it would be syntax I personally am unlikely to ever use, and probably won't even see very often). I'm just trying to summarize some of the themes of the discussion FYI. Footnotes: [1] Addition of a special NULL object was proposed, IIRC, but I forget why that was considered a bad idea. [2] On the other hand, ':=' got in even though that is what '=' is for. That's a precedent that PEP 505 didn't have, turning a statement into an expression. ___ 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/GGOKSHNRRKARMU3J654DFETCCFRNRLMN/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: An alternative way of defining properties (warning: contains creative abuse of the class statement)
My personal feeling: I would love this idea (DRY gets me almost every time) if it weren't for that awful, terrible `class` keyword hanging out there. I wouldn't call using class this way "abuse", exactly, but it could be a potential use for an old idea raised more than once in the past: some kind of submodule or namespace definition statement: class Test: @Property ns foo: # ns a new syntax meaning a namespace, or "submodule", object """Docstring for foo""" def fget(self): print("Getting foo") return self._foo def fset(self, x): print("Setting foo to", x) self._foo = x --- Ricky. "I've never met a Kentucky man who wasn't either thinking about going home or actually going home." - Happy Chandler On Thu, Jul 2, 2020 at 1:46 PM Matthew Einhorn wrote: > > > On Thu, Jul 2, 2020, 6:30 AM Greg Ewing > wrote: > >> On 2/07/20 8:04 pm, Serhiy Storchaka wrote: >> > It has a problem with pickling (it is solvable). >> >> Can you elaborate? The end result is a property object just the >> same as you would get from using @property or calling property >> directly. I don't see how it can have any pickling problems >> beyond what properties already have. >> >> > The larger problem is with using private (double underscored) variables >> > and super(). >> >> I don't know what you're talking about here. I didn't use any >> double-underscore names in my example. >> > > I think what he may have meant is that if you tried accessing a > double-underscore property of the outer class from the get/set methods, it > won't properly de-mangle. > > Similarly, if you wanted to overwrite a property by using this property > approach in the sub-class, but also call super for the parent's class > property getter from within the get/set this wouldn't work!? > >> ___ > 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/ZN77S63ZWLCEG4NAEQAWEWP4MAXXGQ3B/ > 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/NJ43ENGBR7WDID6GX4Q3WO3IUQPQLBCQ/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Else assert statement
> Assertions aren't guaranteed to be executed and thus should never be used where raising an error is required. Hence *roughly* equivalent to. Perhaps for this reason the second version would be confusing and should not be used. > `else: raise SomeError('reason')` already has the desired effect, and it's plenty readable. If this is what people think then I don't have a problem with that and there is no need for change. ___ 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/IVITNVUCYEINEQKDDH4SNIF4O6OFJMYO/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Else assert statement
To be more specific, if the last `elif` condition permits all remaining permissible conditions (which I suppose would just be whatever is asserted by the proposed syntax), then the else block can just be the raising of the exception. On Thu, Jul 2, 2020, 7:52 PM Steele Farnsworth wrote: > Assertions aren't guaranteed to be executed and thus should never be used > where raising an error is required. > > `else: raise SomeError('reason')` already has the desired effect, and it's > plenty readable. > > On Thu, Jul 2, 2020, 7:46 PM Artemis wrote: > >> Often, I know that a variable should have one of a set of values, and I >> want to determine which one, with an if/elif/else clause. This looks >> something like this: >> ``` >> if foo == 1: >> # do a >> elif foo == 2: >> # do b >> elif foo == 3: >> # do c >> else: >> raise ValueError('foo must be 1, 2 or 3') >> ``` >> Sometimes, I just do >> ``` >> if foo == 1: >> # do a >> elif foo == 2: >> # do b >> else: >> # do c >> ``` >> But this is less readable and allows errors to slip past. My proposal is >> to allow the following syntax: >> ``` >> if foo == 1: >> # do a >> elif foo == 2: >> # do b >> else foo == 3: >> # do c >> ``` >> Or perhaps the more readable version: >> ``` >> if foo == 1: >> # do a >> elif foo == 2: >> # do b >> else assert foo == 3: >> # do c >> ``` >> Both of these options are backward compatible, since currently nothing is >> allowed between the `else` and the `:`. >> This would be roughly equivalent to >> ``` >> if foo == 1: >> # do a >> elif foo == 2: >> # do b >> else: >> assert foo == 3 >> # do c >> ``` >> But shorter and more readable, since it puts the assertion at the same >> levels as the others. Thoughts? >> ___ >> 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/ZKAQK7YTOR2GVVFZFVO3U22WYJHVC3KE/ >> 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/O44732WE7XIF5YRO2JFWDPXMOSSHII4A/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Else assert statement
Assertions aren't guaranteed to be executed and thus should never be used where raising an error is required. `else: raise SomeError('reason')` already has the desired effect, and it's plenty readable. On Thu, Jul 2, 2020, 7:46 PM Artemis wrote: > Often, I know that a variable should have one of a set of values, and I > want to determine which one, with an if/elif/else clause. This looks > something like this: > ``` > if foo == 1: > # do a > elif foo == 2: > # do b > elif foo == 3: > # do c > else: > raise ValueError('foo must be 1, 2 or 3') > ``` > Sometimes, I just do > ``` > if foo == 1: > # do a > elif foo == 2: > # do b > else: > # do c > ``` > But this is less readable and allows errors to slip past. My proposal is > to allow the following syntax: > ``` > if foo == 1: > # do a > elif foo == 2: > # do b > else foo == 3: > # do c > ``` > Or perhaps the more readable version: > ``` > if foo == 1: > # do a > elif foo == 2: > # do b > else assert foo == 3: > # do c > ``` > Both of these options are backward compatible, since currently nothing is > allowed between the `else` and the `:`. > This would be roughly equivalent to > ``` > if foo == 1: > # do a > elif foo == 2: > # do b > else: > assert foo == 3 > # do c > ``` > But shorter and more readable, since it puts the assertion at the same > levels as the others. Thoughts? > ___ > 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/ZKAQK7YTOR2GVVFZFVO3U22WYJHVC3KE/ > 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/MQYWGD6VUM2IFJ6HGIWKYRGPJOOCUB3G/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Else assert statement
Often, I know that a variable should have one of a set of values, and I want to determine which one, with an if/elif/else clause. This looks something like this: ``` if foo == 1: # do a elif foo == 2: # do b elif foo == 3: # do c else: raise ValueError('foo must be 1, 2 or 3') ``` Sometimes, I just do ``` if foo == 1: # do a elif foo == 2: # do b else: # do c ``` But this is less readable and allows errors to slip past. My proposal is to allow the following syntax: ``` if foo == 1: # do a elif foo == 2: # do b else foo == 3: # do c ``` Or perhaps the more readable version: ``` if foo == 1: # do a elif foo == 2: # do b else assert foo == 3: # do c ``` Both of these options are backward compatible, since currently nothing is allowed between the `else` and the `:`. This would be roughly equivalent to ``` if foo == 1: # do a elif foo == 2: # do b else: assert foo == 3 # do c ``` But shorter and more readable, since it puts the assertion at the same levels as the others. Thoughts? ___ 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/ZKAQK7YTOR2GVVFZFVO3U22WYJHVC3KE/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Best approach for opaque PyObject
On Thu, Jul 2, 2020, at 16:04, William Pickard wrote: > The goal as it stands is to make PyObject an opaque type (interpreted > to mean, "incomplete type"), but there is a blocking problem to > accomplishing that. > > Functions/Macros like PY_TYPE require a complete PyObject. Is it acceptable if the performance hit only applies to external [not part of the python implementation] callers? The macro could be defined as to call an exported function from external code but as its current definition within the python implementation. I do think there's a much bigger problem, though... if PyObject is opaque, then extension modules cannot define their own types, since the definition of any extension type has to begin with PyObject_HEAD. It could be replaced by a "semi-opaque" definition of the same size and alignment, but would that solve whatever problem making PyObject opaque is intended to solve? ___ 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/SCKWJFK4BFU7Q25O4OYSULYKRQQMZO4F/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Best approach for opaque PyObject
The goal as it stands is to make PyObject an opaque type (interpreted to mean, "incomplete type"), but there is a blocking problem to accomplishing that. Functions/Macros like PY_TYPE require a complete PyObject. There is 3 ways we can solve this problem: 1) Dump to & export from the Python DLL. - This will created performance overhead that can scale worse and worse the more they're used. 2) Dump to a static library. - This has a toss up on saving performance or sharing #1's problem depending on the compiler and options used. 3) Dump to precompiled headers. - My limited understanding of precompiled headers suggests we can eliminate the need of LTCG, but compilers CAN impose restrictions on their usage (MSVC for sure has restrictions). What would be the best approach to go with? Ultimately, the end result should have roughly the same performance rating as current non limited code. ___ 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/FP45PSSPZSDBJYOP4IAQ3IBLNBQREYBD/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: What about having a .get(index, default) method for arrays like we have for dicts?
On Thu, Jul 2, 2020 at 9:33 PM Daniel. wrote: > Em ter., 30 de jun. de 2020 às 15:49, Alex Hall > escreveu: > >> I think I'm missing something. Daniel wants a `list.get` method with >> similar semantics to `dict.get`. So instead of writing: >> >> ``` >> try: >> x = lst[i] >> except IndexError: >> x = default >> ``` >> >> one could write `x = lst.get(i, default)`. How would you rewrite that >> with PEP 505? >> > With PEP 505 is not possible to have an arbitrary default as the result of > null coalesced expression will be None if a None is found. The lst.get(i) > would be rewritten as lst?[i], and composing dct.get('foo', []).get(0, > []).get('bar') would be something like dct?['foo']?[0]?['bar'] > No, that's not right. `dct?['foo']` translates to `dct['foo'] if dct is not None else None`, which is very different from `dct.get('foo')`. Similarly `lst?[i]` is for when `lst` might be None, not empty. All PEP 505 gives you in the case where keys might be missing or lists might be empty is that you can write `.get` without defaults, e.g. `dct.get('foo')?.get(0)?.get('bar')`. I would quite like to have PEP 505, but I don't know how to revive it. And I'm not surprised that it's deferred, there's generally reluctance to add new syntax, especially symbols. On the other hand, `list.get` seems very doable to me. It's not new syntax. It would be extremely easy to learn for anyone familiar with `dict.get`, which is pretty much essential knowledge. You'd probably have some people guessing it exists and using it correctly without even seeing it first in other code or documentation. I haven't seen anyone in this thread suggesting any cost or downside of adding the method, just people asking if it would be useful. I feel like I answered that question pretty thoroughly, then the thread went quiet. ___ 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/L6M7AKQ7L6BBU5YRKAET6HPQFFDFR7TS/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: What about having a .get(index, default) method for arrays like we have for dicts?
Em ter., 30 de jun. de 2020 às 15:49, Alex Hall escreveu: > I think I'm missing something. Daniel wants a `list.get` method with > similar semantics to `dict.get`. So instead of writing: > > ``` > try: > x = lst[i] > except IndexError: > x = default > ``` > > one could write `x = lst.get(i, default)`. How would you rewrite that with > PEP 505? > With PEP 505 is not possible to have an arbitrary default as the result of null coalesced expression will be None if a None is found. The lst.get(i) would be rewritten as lst?[i], and composing dct.get('foo', []).get(0, []).get('bar') would be something like dct?['foo']?[0]?['bar'], from what I read, this is very terse and terse is good in most cases good in my opinion. It removes the error handling noise by replacing it by one char I'm repeating myself here, but again, the use case is to fetch deedly nested data. All this talk make me notice that IndexError, and KeyError are LookupError instances but AttributeError is not, still pep 505 have an elegant solution for all these three. Also it handles the None?.method() case, when something return an object or None and you want to call a method on this if is not None. I think we should put more effort on pep 505 > > I've also wanted this a couple of times, although I can't remember the > reason. It's not just about traversing incomplete nested data structures. I > don't see much disadvantage since the analogy with `dict.get` would make it > very easy to learn and understand, to the point that I've wondered why this > doesn't exist already. > > On Sat, Jun 27, 2020 at 5:09 PM Guido van Rossum wrote: > >> Please read PEP 505 before rehashing this old idea. >> >> On Sat, Jun 27, 2020 at 06:35 Daniel. wrote: >> >>> When I need to traverse nested dicts, is a common pattern to do >>> >>> somedict.get('foo', {}).get('bar', {}) >>> >>> But there is no such equivalent for arrays, wouldn't be nice if we can >>> follow >>> >>> somedict.get('foo', {}).get('bar', []).get(10) ... ? >>> >>> What I do in this case is surround with try/except IndexError and set >>> some variable to None, or wrap the try/except block in a function. But this >>> is noise in my opinion, I just want to follow the same reasoning that I >>> have with dicts: I'm searching for some path deep nested, and want a >>> default if not found. >>> >>> What do you think? >>> >>> Regards >>> >>> -- >>> “If you're going to try, go all the way. Otherwise, don't even start. >>> ..." >>> Charles Bukowski >>> ___ >>> 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/LLK3EQ3QWNDB54SEBKJ4XEV4LXP5HVJS/ >>> Code of Conduct: http://python.org/psf/codeofconduct/ >>> >> -- >> --Guido (mobile) >> ___ >> 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/L64EPHNKVRFLSBJE53GPQ4JFNVNOPH7U/ >> Code of Conduct: http://python.org/psf/codeofconduct/ >> > -- “If you're going to try, go all the way. Otherwise, don't even start. ..." Charles Bukowski ___ 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/UOJL3T5FSLDZ7HY4WGRT4LCMLWSFMNF6/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: What about having a .get(index, default) method for arrays like we have for dicts?
Em qua, 1 de jul de 2020 00:56, David Lowry-Duda escreveu: > Very similar things could be said about dict.get too, no? It's easy to > write your own function that does the same thing or to catch an > exception. > > On the other hand, it seems far more likely to miss keys in a dictionary > than it is to repeatedly mistake indices in a list. > > Which would be the use cases for this feature? > > > > I can't think of one. > > I've never missed this feature either. But I would also be interested in > hearing a dream use case. > The usecase is extracting deeply nested data from parsed json. Missing keys are something that happens on dicts, I want something that is able to extract data from parsed json, that eliminates the error handling noise. All this talk elucidates me that this is possible try: v = foo.bar['tar'][0]['zar'] except (LookupError, AttributeError): v = None would suffice in all cases, > > - DLD > > > -- > David Lowry-Duda > ___ > 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/EUCNY7QZSADRHIGH5KK6BECYGXVDQDRF/ > 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/NTD7HRZE4Q3J77D7RTJRLKJ4RX7Y4AEQ/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: An alternative way of defining properties (warning: contains creative abuse of the class statement)
On Thu, Jul 2, 2020, 6:30 AM Greg Ewing wrote: > On 2/07/20 8:04 pm, Serhiy Storchaka wrote: > > It has a problem with pickling (it is solvable). > > Can you elaborate? The end result is a property object just the > same as you would get from using @property or calling property > directly. I don't see how it can have any pickling problems > beyond what properties already have. > > > The larger problem is with using private (double underscored) variables > > and super(). > > I don't know what you're talking about here. I didn't use any > double-underscore names in my example. > I think what he may have meant is that if you tried accessing a double-underscore property of the outer class from the get/set methods, it won't properly de-mangle. Similarly, if you wanted to overwrite a property by using this property approach in the sub-class, but also call super for the parent's class property getter from within the get/set this wouldn't work!? > ___ 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/ZN77S63ZWLCEG4NAEQAWEWP4MAXXGQ3B/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: An alternative way of defining properties (warning: contains creative abuse of the class statement)
On Thu, Jul 2, 2020 at 8:38 PM Greg Ewing wrote: > > On 2/07/20 9:45 pm, Chris Angelico wrote: > > On Thu, Jul 2, 2020 at 7:41 PM Alex Hall wrote: > >> > >> On Thu, Jul 2, 2020 at 11:33 AM Chris Angelico wrote: > >>> > >>> What's the idea being discussed? AIUI there's no need or request to > >>> change the language/stdlib, but maybe I'm misreading. > >> > >> Ah, now I understand. I did automatically assume that Greg was proposing > >> adding this to the stdlib or something, but maybe I only assumed that > >> because it was in the list. > > > > Could be that I'm the one misunderstanding here, but only Greg can > > answer that question :) > > I was thinking something like it might become a candidate for stdlib > inclusion, if it wasn't universally hated for abusing the class > statement. > Let's get concrete then. Suppose that the property constructor recognized a special one-argument form: if it has an fget attribute, it fetches its details from the fget, fset, fdel, and __doc__ attributes of that object. That way, it can be used in three ways: a standard constructor that does all the work with up to four arguments, the decorator form (which is the same as the one-arg form initially, but then you can use its setter decorator), and the class form. class Test: x = property(lambda self: 42, lambda self, val: print("Setting to", val)) @property def y(self): return 42 @y.setter def y(self, val): print("Setting to", val) # the theoretical one @property class z: def fget(self): return 42 def fset(self, val): print("Setting to", val) Since functions won't normally have fset attributes, this should be fairly safe - technically it'd be backward incompatible, but it's highly unlikely to break any real-world code. I don't write a lot of properties with setters, so I can't speak to the value of this, but it is at least plausible. (If you'd prefer to use "get" or "getter" or something in place of "fget", that would work fine. I used the same name as the keyword arg to property itself, but it can be anything.) 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/AVYCCI42LUQZFVODRCTL5YCFUJX4I5VC/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: An alternative way of defining properties (warning: contains creative abuse of the class statement)
Haha, I had no idea! That's great. fyi, judicious use of cython allowed our python team to build python components that far outperformed their java counterparts in some real-time middle-office financial processing jobs for a really large client. So thank you. I can see why using the standard python syntax might be considered better than the more elegant custom version, but yes, it's a bit sad Steve On Thu, Jul 2, 2020 at 12:27 PM Greg Ewing wrote: > On 2/07/20 10:49 pm, Stestagg wrote: > > Coincidentally, cython has a custom, deprecated syntax for properties > > that is actually pretty similar > > Not entirely a coincidence -- I invented that syntax for Pyrex, > and Cython inherited it. > > I'm a little disappointed to hear it's been deprecated. :-( > > -- > Greg > ___ > 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/YPSI34LADS3A2HR4MXB6B3MXZHXXKNT6/ > 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/ISR7PUNHBETV5HBPERTBOZFBJYATHEVO/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: An alternative way of defining properties (warning: contains creative abuse of the class statement)
On 2/07/20 10:49 pm, Stestagg wrote: Coincidentally, cython has a custom, deprecated syntax for properties that is actually pretty similar Not entirely a coincidence -- I invented that syntax for Pyrex, and Cython inherited it. I'm a little disappointed to hear it's been deprecated. :-( -- Greg ___ 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/YPSI34LADS3A2HR4MXB6B3MXZHXXKNT6/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: An alternative way of defining properties (warning: contains creative abuse of the class statement)
Coincidentally, cython has a custom, deprecated syntax for properties that is actually pretty similar, and nice: cdef class Spam: property cheese: "A doc string can go here." def __get__(self): # This is called when the property is read. ... def __set__(self, value): # This is called when the property is written. ... def __del__(self): # This is called when the property is deleted. https://cython.readthedocs.io/en/latest/src/userguide/extension_types.html#properties I don't think the benefits are worth a core python change, but great minds.. Steve On Thu, Jul 2, 2020 at 11:42 AM Greg Ewing wrote: > On 2/07/20 9:00 pm, Steven D'Aprano wrote: > > > Perhaps Greg meant to say *up to* rather than "no less". > > What I said is true for sufficiently small values of 5. :-) > > You're right that it depends on how many operations you > want. For reading and writing it's 3; if you want deleting > as well it's 5. > > But 3 is still a lot less DRY than 1. > > -- > Greg > ___ > 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/4QVMNKAU7UXX6LHWWVYYFFVME3GXYVDW/ > 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/IXZQZT3D2V7LE5EENHBLUBGGI3M4HJUJ/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: An alternative way of defining properties (warning: contains creative abuse of the class statement)
On 2/07/20 9:00 pm, Steven D'Aprano wrote: Perhaps Greg meant to say *up to* rather than "no less". What I said is true for sufficiently small values of 5. :-) You're right that it depends on how many operations you want. For reading and writing it's 3; if you want deleting as well it's 5. But 3 is still a lot less DRY than 1. -- Greg ___ 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/4QVMNKAU7UXX6LHWWVYYFFVME3GXYVDW/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: An alternative way of defining properties (warning: contains creative abuse of the class statement)
On 2/07/20 9:45 pm, Chris Angelico wrote: On Thu, Jul 2, 2020 at 7:41 PM Alex Hall wrote: On Thu, Jul 2, 2020 at 11:33 AM Chris Angelico wrote: What's the idea being discussed? AIUI there's no need or request to change the language/stdlib, but maybe I'm misreading. Ah, now I understand. I did automatically assume that Greg was proposing adding this to the stdlib or something, but maybe I only assumed that because it was in the list. Could be that I'm the one misunderstanding here, but only Greg can answer that question :) I was thinking something like it might become a candidate for stdlib inclusion, if it wasn't universally hated for abusing the class statement. -- Greg ___ 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/27SAVMOC2A7PRSARKUWHB6FI6NTIAL2H/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: An alternative way of defining properties (warning: contains creative abuse of the class statement)
On 2/07/20 8:04 pm, Serhiy Storchaka wrote: It has a problem with pickling (it is solvable). Can you elaborate? The end result is a property object just the same as you would get from using @property or calling property directly. I don't see how it can have any pickling problems beyond what properties already have. The larger problem is with using private (double underscored) variables and super(). I don't know what you're talking about here. I didn't use any double-underscore names in my example. -- Greg ___ 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/HX77GNJEZZH56VWVWL4U253YZUPQD2UT/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: An alternative way of defining properties (warning: contains creative abuse of the class statement)
On Thu, Jul 2, 2020 at 11:33 AM Chris Angelico wrote: > On Thu, Jul 2, 2020 at 7:06 PM Alex Hall wrote: > > > > On Thu, Jul 2, 2020 at 9:34 AM Chris Angelico wrote: > >> > >> (Not sure why this is on python-ideas - wouldn't python-list be more > >> appropriate? Keeping it where it is for now though.) > > > > > > As someone not familiar with the other lists...why? It's a proposal of > an idea that could use some debate. Isn't this the perfect place? > > > > What's the idea being discussed? AIUI there's no need or request to > change the language/stdlib, but maybe I'm misreading. This is a cute > showcase of how a class namespace can be used to gather multiple > functions together and build a property with them; it already works > without any changes. So it's a great thing to discuss, but with no > changes being proposed, it's not really an idea for the language. On > python-list, there'll be more people, many of whom wouldn't think to > hang out here, but could still appreciate (a) this cool way of doing > properties, and (b) the more general notion that a decorated class or > metaclass can be used for this kind of very powerful namespacing. > Ah, now I understand. I did automatically assume that Greg was proposing adding this to the stdlib or something, but maybe I only assumed that because it was in the list. ___ 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/FPJZIWDE33YGYB6RR3WYD5ZTMN5FMQSZ/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: An alternative way of defining properties (warning: contains creative abuse of the class statement)
On Thu, Jul 2, 2020 at 7:41 PM Alex Hall wrote: > > On Thu, Jul 2, 2020 at 11:33 AM Chris Angelico wrote: >> >> What's the idea being discussed? AIUI there's no need or request to >> change the language/stdlib, but maybe I'm misreading. > > Ah, now I understand. I did automatically assume that Greg was proposing > adding this to the stdlib or something, but maybe I only assumed that because > it was in the list. > Could be that I'm the one misunderstanding here, but only Greg can answer that question :) 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/ZCGPV3VGS6TH45MXPCX4HMZRQTE5GYY2/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: An alternative way of defining properties (warning: contains creative abuse of the class statement)
On Thu, Jul 2, 2020 at 7:06 PM Alex Hall wrote: > > On Thu, Jul 2, 2020 at 9:34 AM Chris Angelico wrote: >> >> (Not sure why this is on python-ideas - wouldn't python-list be more >> appropriate? Keeping it where it is for now though.) > > > As someone not familiar with the other lists...why? It's a proposal of an > idea that could use some debate. Isn't this the perfect place? > What's the idea being discussed? AIUI there's no need or request to change the language/stdlib, but maybe I'm misreading. This is a cute showcase of how a class namespace can be used to gather multiple functions together and build a property with them; it already works without any changes. So it's a great thing to discuss, but with no changes being proposed, it's not really an idea for the language. On python-list, there'll be more people, many of whom wouldn't think to hang out here, but could still appreciate (a) this cool way of doing properties, and (b) the more general notion that a decorated class or metaclass can be used for this kind of very powerful namespacing. 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/VPSNQGMSIKVYRMNJF5CZD5AVJUDUFMJS/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: An alternative way of defining properties (warning: contains creative abuse of the class statement)
On Thu, Jul 2, 2020 at 7:04 PM Steven D'Aprano wrote: > That makes five by my count, however I hardly ever write a deleter so > three is more common, and only occassionally a setter so one is most > common :-) > Well, if you only want a getter, the most common way is fine. But if you then go to add a setter, you have to keep things in sync. 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/57P3IFRKJ5ELWOW7ER6RJWALRHBVHREJ/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: An alternative way of defining properties (warning: contains creative abuse of the class statement)
On Thu, Jul 2, 2020 at 9:34 AM Chris Angelico wrote: > (Not sure why this is on python-ideas - wouldn't python-list be more > appropriate? Keeping it where it is for now though.) > As someone not familiar with the other lists...why? It's a proposal of an idea that could use some debate. Isn't this the perfect place? ___ 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/7CWH3OQW2HA75XZQKWQNLQOSG6AEH4UY/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: An alternative way of defining properties (warning: contains creative abuse of the class statement)
On Thu, Jul 02, 2020 at 11:04:40AM +0300, Serhiy Storchaka wrote: > 02.07.20 10:12, Greg Ewing пише: > >The @property.getter and @property.setter decorators are > >clever, but they have the disadvantage that you end up > >writing the name of the property no less than 5 times, > >all of which have to match. > > 5 times? How is it? Perhaps Greg meant to say *up to* rather than "no less". class MyClass: @property def spam(): ... @spam.setter def spam(self, value): ... @spam.deleter def spam(self): ... That makes five by my count, however I hardly ever write a deleter so three is more common, and only occassionally a setter so one is most common :-) -- Steven ___ 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/ZHPW7YN23FXEZHRJ5IJAYZ66VSMORFUU/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: An alternative way of defining properties (warning: contains creative abuse of the class statement)
02.07.20 10:12, Greg Ewing пише: The @property.getter and @property.setter decorators are clever, but they have the disadvantage that you end up writing the name of the property no less than 5 times, all of which have to match. 5 times? How is it? Thinking there must be a better way, I came up with this: def Property(name, bases, dict): return property(dict.get('get'), dict.get('set')) It has a problem with pickling (it is solvable). The larger problem is with using private (double underscored) variables and super(). ___ 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/S4JP6W7H35CNXWAWNCCWCNMX6RHAZXH3/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: An alternative way of defining properties (warning: contains creative abuse of the class statement)
(Not sure why this is on python-ideas - wouldn't python-list be more appropriate? Keeping it where it is for now though.) On Thu, Jul 2, 2020 at 5:14 PM Greg Ewing wrote: > > The @property.getter and @property.setter decorators are > clever, but they have the disadvantage that you end up > writing the name of the property no less than 5 times, > all of which have to match. > > Thinking there must be a better way, I came up with this: > > def Property(name, bases, dict): > return property(dict.get('get'), dict.get('set')) > > which allows you to write > > class Test: > > class foo(metaclass = Property): > > def get(self): > print("Getting foo") > return self._foo > > def set(self, x): > print("Setting foo to", x) > self._foo = x > > test = Test() > test.foo = 42 > print(test.foo) > > Output: > Setting foo to 42 > Getting foo > 42 > I quite like the use of class blocks as namespaces, but I'm not a fan of metaclassing. A decorated class is way cleaner in the source code. How about this? def Property(ns): return property(*[getattr(ns, k, None) for k in ("fget", "fset", "fdel", "__doc__")]) class Test: @Property class foo: """Docstring for foo""" def fget(self): print("Getting foo") return self._foo def fset(self, x): print("Setting foo to", x) self._foo = x Same output as yours, and it's easy to support fdel, and a docstring. 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/BKEHOXQEHEI44OZFE5U5SG3E3LTCISMW/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] An alternative way of defining properties (warning: contains creative abuse of the class statement)
The @property.getter and @property.setter decorators are clever, but they have the disadvantage that you end up writing the name of the property no less than 5 times, all of which have to match. Thinking there must be a better way, I came up with this: def Property(name, bases, dict): return property(dict.get('get'), dict.get('set')) which allows you to write class Test: class foo(metaclass = Property): def get(self): print("Getting foo") return self._foo def set(self, x): print("Setting foo to", x) self._foo = x test = Test() test.foo = 42 print(test.foo) Output: Setting foo to 42 Getting foo 42 -- Greg ___ 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/LYNBL6D2HFYHQGQCBXFKJO6W3JRZYJZ5/ Code of Conduct: http://python.org/psf/codeofconduct/