[Python-ideas] Re: Add a .whitespace property to module unicodedata
On 6/1/23 11:06, David Mertz, Ph.D. wrote: > I guess this is pretty general for the described need: > > >>> unicode_whitespace = [chr(c) for c in range(0x) if unicodedata.category(chr(c)) == "Zs"] Using the module-level `__getattr__` that could be a lazy attribute. -- ~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/TMHAJMGZH4JHZOIKKWE55ZCF4N4CHGNI/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: len(Enum) should raise TypeError
On 4/1/23 07:45, Richard Hajek wrote: > # Feature or enhancement > > `len(Enum)` has no useful meaning and should therefore raise the appropriate error > > # Pitch > > I cannot figure out any scenario, in which len(Enum) should not raise. Enum is a type and as any other types, such as `len(list)` or `len(dict)`, and should not give any meaningful result on len. Enums are not like any other type in a multitude of ways: `__len__`, `__contains__`, `__getitem__`, etc. Special-casing only `Enum`, `IntEnum`, `StrEnum`, and every other base enum (i.e. no members), would be like special-casing empty lists, empty dicts, empty tuples, etc. -- ~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/YW6PLGLW4N6ZAZWR6ELED2ZIIPL3E4XQ/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Idea: Tagged strings in python
On 12/19/22 13:59, Chris Angelico wrote: > The way things are, a StrEnum or an HTML string will behave *exactly > as a string does*. The alternative is that, if any new operations are > added to strings in the future, they have to be explicitly blocked by > StrEnum or else they will randomly and mysteriously misbehave - or, at > very best, crash with unexpected errors. Which one is more hostile to > subclasses? As Brendan noted, mixed-type enums are special -- they are meant to be whatever they subclass, with a couple extra features/restrictions. Personally, every other time I've wanted to subclass a built-in data type, I've wanted the built-in methods to return my subclass, not the original class. All of which is to say: sometimes you want it one way, sometimes the other. ;-) Metaclasses, anyone? -- ~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/H6TQFFG3QZDNC4EJGROYLJVWU6L57XBA/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: zip(x, y, z, strict=True)
On 12/1/22 11:36, Ram Rachum wrote: > Reviving this thread 2.5 years after I started it just to share this satisfying moment... Very cool! Always enjoyable to benefit from the fruits of one labors. :-) -- ~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/SUNW2FQIPB6IOKIFEULCHPPZL3WUHLVC/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Make dataclass aware that it might be used with Enum
On 7/9/22 12:19, Steve Jorgensen wrote: > [...] It works great to combine them by defining the dataclass as a mixin for the Enum class. Why would > it not be good to include that as an example in the official docs, assuming (as I believe) that it is a > particularly useful combination? Do you have some real-world examples that show this? -- ~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/OSGWU6QMAN34TNQHK2ZVN5K3EPKGRGZX/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Make dataclass aware that it might be used with Enum
On 7/7/22 18:22, Steve Jorgensen wrote: > After some playing around, I figured out a pattern that works without any changes to the > implementations of `dataclass` or `Enum`, and I like this because it keeps the 2 kinds of > concern separate. Maybe I'll try submitting an MR to add an example like this to the > documentation for `Enum`. > > In [1]: from dataclasses import dataclass > > In [2]: from enum import Enum > > In [3]: @dataclass(frozen=True) > ...: class CreatureDataMixin: > ...: size: str > ...: legs: int > ...: > > In [4]: class Creature(CreatureDataMixin, Enum): > ...: BEETLE = ('small', 6) > ...: DOG = ('medium', 4) > ...: > > In [5]: Creature.DOG > Out[5]: Creature(size='medium', legs=4) I'm impressed that you found a way to make it work. Be aware that some of the bug-fixing in 3.11 has changed the resulting repr() -- the above now looks like: It would be possible to have Enum check to see if the data type is a dataclass, and then see if the repr is set to be automatically created: >>> CreatureDataMixin.__dataclass_params__ _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=True) I'll have to look into that. It does seem like a lot of extra work, or at least no less work, than just writing an `__init__` in the enum class directly. -- ~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/X2KBATIBRGAPSVYNAWX77WCRIPUMQKLX/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Make dataclass aware that it might be used with Enum
On 7/8/22 19:50, Ethan Furman wrote: > The repr from a combined dataclass/enum looks like a dataclass, giving no clue that the > object is an enum, and omitting any information about which enum member it is and which > enum it is from. Fixed in 3.11: `` -- ~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/2CURYFJAFITUMBVTSJMVJSOBOVL2OXUA/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Make dataclass aware that it might be used with Enum
On 7/7/22 09:01, Steve Jorgensen wrote: > Actually, maybe these are fundamentally incompatible? `@dataclass` is a decorator, so it > acts on the class after it was already defined, but `Enum` acts before that when `@dataclass` > cannot have not generated the `__init__` yet. Right? Correct. -- ~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/TXBQEVYMFWDIKNXU6X6IASU22G42PWFG/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Make dataclass aware that it might be used with Enum
On 7/6/22 17:01, Steve Jorgensen wrote: > Perhaps, this has already been addressed in a newer release (?) but in Python 3.9, making > `@dataclass` work with `Enum` is a bit awkward. > > Currently, it order to make it work, I have to: > 1. Pass `init=False` to `@dataclass` and hand-write the `__init__` method > 2. Pass `repr=False` to `@dataclass` and use `Enum`'s representation or write a custom __repr__ > > Example: > In [72]: @dataclass(frozen=True, init=False, repr=False) > ...: class Creature(Enum): > ...: legs: int > ...: size: str > ...: Beetle = (6, 'small') > ...: Dog = (4, 'medium') > ...: def __init__(self, legs, size): > ...: self.legs = legs > ...: self.size = size > ...: > > In [73]: Creature.Dog > Out[73]: So why use dataclass then? class Creature(Enum): Beetle = (6, 'small') Dog = (4, 'medium') def __init__(self, legs, size): self.legs = legs self.size = size and >>> list(Creature) [, ] >>> Creature.Beetle.size 'small' >>> Creature.Beetle.legs 6 It looks like dataclass was just making you do a bunch of extra work. -- ~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/X5UCN42LFGSGISWD62SUP2BU4WDRGWDM/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Make dataclass aware that it might be used with Enum
On 7/7/22 09:01, Steve Jorgensen wrote: > Actually, maybe these are fundamentally incompatible? Their intended use seems fundamentally incompatible: - dataclass was designed for making many mutable records (hundreds, thousands, or more) - enum was designed to make a handful of named constants (I haven't yet seen one with even a hundred elements) The repr from a combined dataclass/enum looks like a dataclass, giving no clue that the object is an enum, and omitting any information about which enum member it is and which enum it is from. Given these conflicts of interest, I don't see any dataclass examples making it into the enum documentation. -- ~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/6CIPPTP2Z42GVUIVOUXZ7BW46DB5HWEZ/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Time to relax some restrictions on the walrus operator?
On 5/8/22 05:08, Valentin Berlier wrote: > This would make it really useful in if statements and list comprehensions. Here are a couple motivating examples: > > # Buy every pizza on the menu > cost_for_all_pizzas = sum( > price for food in menu > if ({"type": "pizza", "price": price} := food) > ) What exactly is that last line testing, and how does it differentiate between "pizza" and, say, "salad"? -- ~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/UUGWJOOOLKTMMG65QDTWYOPP5QF23MYI/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Auto assignment of attributes
On 5/7/22 06:24, Chris Angelico wrote: > On Sat, 7 May 2022 at 23:15, Stephen J. Turnbull wrote: >> >> def foo(self, x, y): >> x.y = y >> >> is not a pattern I can recall ever seeing > > I'd define it very simply. For positional args, these should be > exactly equivalent: > > def func(self, x, x.y): > ... > > def func(*args): > self, x, x.y = args > ... Simple or not, I don't think Python needs that much 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/AWRAA7MTXHV5SXCBVSK4BMSO2G3EAKX5/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Auto assignment of attributes
On 5/2/22 23:21, Christopher Barker wrote: > But yes, there are many use cases not suited to dataclasses. The question is how many of these would > rap parge benefit from auto-assigning syntax? How did you get to "rap parge" from "reap the" ? On 5/2/22 20:32, Christopher Barker wrote: > Anyway, I think thee we conversation has moved beyond this. And "thee we" from "that the" ? Do we get bonus points if we break the code? ;-) -- ~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/U7YHFKV7SBUCQTXM3F3A7SP3M7VIKSBZ/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Auto assignment of attributes
On 5/1/22 00:21, Christopher Barker wrote: > On Sat, Apr 30, 2022 at 2:17 PM Pablo Alcain wrote: >> It shows that out of 20k analyzed classes in the selected libraries (including black, >> pandas, numpy, etc), ~17% of them could benefit from the usage of auto-assign syntax. > > I only read English, and haven't studied the coe, so I don't know how that works, but > assuming it's accurately testing for the simple cases that auto-assigning could work for; > > That's not that much actually -- for approx every six-parameter function, one of them > could be auto-assigned.or for every six functions, one could make good use of auto- > assignment (and maybe be a dataclass?) I think you place too much emphasis on dataclasses -- none of my projects use them, nor could they. Going through a one of my smaller projects, this is what I found: - number of `__init__`s: 11 - number of total params (not counting self): 25 - number of those params assigned as-is: 19 - number of `__init__`s where all are assigned as-is: 6 - number of non-`__init__`s where this would useful: 0 > And I'm not trying to be a Negative Nelly here -- I honestly don't know, I actually > expected it to be higher than 17% -- but in any case, I think it should be higher than > 17% to make it worth a syntax addition. 17% is a massive amount of code. > But pandas and numpy may not be the least bit representative [...]? This would not be the first time Python was improved to help the scientific community. My own thoughts about the proposal: It seems interesting, and assigning as-is arguments is a chore -- but I'm not sure using up a token to help only one method per class is a good trade. -- ~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/2GR5G67IKJZDSFU4QYJQF7R4BCZUZPMJ/ Code of Conduct: http://python.org/psf/codeofconduct/
[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 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: 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: Native support for units
On 4/12/22 00:57, Stephen J. Turnbull wrote: Ethan Furman writes: 15mpg * 7l == how many miles? Now it's my turn to not understand the point of this example. My point is that when an object is instantiated it can normalize its arguments, and that that normalization should happen with the original value (7 above, not 105), so when I put the above into the REPL I get `27 miles` instead of `105 l*mpg`. Now, it could easily be that more advanced uses of units (torque vs force? or whatever was mentioned some time ago) would work better with the intermediate results being more in flux (quantum mechanics, anyone? heh) with the final units being selected later (perhaps somebody wants kilometers instead of miles in the above example). To rephrase my original point: `7_litres` is a different thing than `105_litres_mpg` -- is that a meaningless difference? I don't know. -- ~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/R2QPBEEXQHSST2OH4KTTHJVVGFGGQDPS/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Custom literals, a la C++
On 4/11/22 11:06, Chris Angelico wrote: Steven is, as are a few who have agreed that namespaces are the One True Way™ to do things. That seems a grossly unfair characterization of those who don't agree with you. I think everyone should take a break from this thread -- it is apparent that no one is convincing any one else, so the final decision will be by the SC (assuming a PEP is ever made). -- ~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/EVAFFRPJ4VG2G7X323QDNY263IL6AGJ2/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Native support for units [was: custom literals]
On 4/10/22 21:33, Stephen J. Turnbull wrote: I guess you could call the associative law of multiplication "dumb luck", but most mathematicians will consider that hate speech. My apologies for not understanding your example. The counter example I had in my head, and should have written down, was something like: 15mpg * 7l == how many miles? where mpg = miles per gallons l = litres I'm pretty sure the answer there is not 105. -- ~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/OGHZSHZZEVHP4MLWXZSH45DGZYO7WDC6/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Custom literals, a la C++
On 4/10/22 14:09, Chris Angelico wrote: On Mon, 11 Apr 2022 at 06:48, Ethan Furman wrote: On 4/10/22 10:17, Chris Angelico wrote: On Mon, 11 Apr 2022 at 02:59, Christopher Barker wrote: But if I did that, then one lib registering my units with the global repository might break some other lib's use of the global repository. Then... libraries should not register units unless it's at the behest of the application? That's exactly what I've been saying. If the library cannot register its version of units, how can it use units internally? Probably the same way that it's always been possible - with clunkier syntax and explicit multiplications. I'm not sure. So mostly with none of the benefits of the new systax. Do you actually have a use-case where a library needs to do unit-aware arithmetic independently of the application, At this point I am not a unit user, but it seems that several who are would like finer grained control, and you are arguing that global is fine; they offer json as an example where the application imposing global settings on their activities would really mess them up, and you don't seem to be hearing/acknowledging that. -- ~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/664UOWVBMFB77R3SISHUFE32NDRSMIPL/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Native support for units [was: custom literals]
On 4/9/22 21:17, Stephen J. Turnbull wrote: if 12*u.mm * 42*u.MFr == 502*u.foo: print('Well done!') That would work fine for me. But I can see why somebody who frequently uses interactive Python as a scientific calculator would prefer to write if 12 m/s * 42 s == 502 m: print('Well done!') with the base SI repertoire (a dozen or so prefixes and 7 units) in builtins. Part of the argument as well, I think, is that the top expression would be parsed as: ((12 * u.m) * 42) * u.MFr which, if actually equal to 502*u.foo, is dumb luck. -- ~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/NL5CLKGOUMHCHJIITEM5XUG5L2D2XPCK/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Custom literals, a la C++
On 4/10/22 10:17, Chris Angelico wrote: On Mon, 11 Apr 2022 at 02:59, Christopher Barker wrote: But if I did that, then one lib registering my units with the global repository might break some other lib's use of the global repository. Then... libraries should not register units unless it's at the behest of the application? That's exactly what I've been saying. If the library cannot register its version of units, how can it use units internally? -- ~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/WHCLRVERUCZLDHFWT3OFFQC3NLDCVCXR/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Native support for units [was: custom literals]
On 4/6/22 08:50, Brian McCall wrote: > Alright, now let's look at an example. Again, it's not my best, let's go with it. This is just > a calculation of the expected number of photons to reach a pixel through a camera of a given > f-number (F). I mentioned this has bitten me before. All that means is that based on a set of > simulations, we though something was possible, spent a few weeks building a prototype, got > results that made no sense, and then realized that there was a unit error in the original > feasibility analysis. That one was on me, and since I am a capable programmer, I ought to have > been using a units package. Thank you for all the examples, that should help a lot. Out of curiosity, those are the corrected versions of the code? Where was the mistake in the original? -- ~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/2HLNUKMBV6SZHCKKI2YRID7EP76KETYC/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Native support for units [was: custom literals]
On 4/4/22 13:31, David Mertz, Ph.D. wrote: > You should probably change the thread subject to "All-and-only 7 SI units" if that's what you mean. While I'm sure SI would be very useful, I suspect that any system will have to be useful for a much broader audience to be accepted; given the vast amount of units, I suspect individual libraries will be needed for each area/discipline. So what hooks does Python need to provide to make such a thing feasible, easy to use, and, eventually if not immediately, performant? One idea: have a `unit` attribute, and that attribute keeps track of the units so far in the operations: [quick PoC] class TaggedInt(int): # def __new__(cls, *args, unit=None, **kwds): ti = int.__new__(cls, *args, **kwds) if unit is None: unit = () elif not isinstance(unit, tuple): unit = (unit, ) ti.unit = unit return ti # def __mul__(self, other): other_unit = getattr(other, 'unit', None) if other_unit is None: unit = self.unit else: unit = self.condense(self.unit, '*', other_unit) ti = TaggedInt(int.__mul__(self, other), unit=unit) return ti # def __rmul__(self, other): other_unit = getattr(other, 'unit', None) if other_unit is None: unit = self.unit else: unit = self.condense(other_unit, '*', self.unit) ti = TaggedInt(int.__mul__(self, other), unit=unit) return ti # def __repr__(self): return '%s %s' % (int.__repr__(self), ''.join(str(u) for u in self.unit)) # def condense(*args): result = [] for arg in args: if isinstance(arg, tuple) and len(arg) == 1: result.append(arg[0]) else: result.append(arg) return tuple(result) in use: >>> to_home = TaggedInt(5, unit='km') >>> to_home 5 km >>> # home and back >>> 2 * to_home 10 km >>> # big square >>> to_home * to_home 25 km*km >>> _.unit ('km', '*', 'km') Beyond that, do we make Python smart enough to, for example, convert `km*km` to `km^2`, or do we let libraries provide their own functions? I'm inclined to let libraries provide their own, as they could also implement unit conversions as desired. -- ~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/QCODSL65G6MRAGOA36KY4RPIPOZRARIF/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Native support for units [was: custom literals]
On 4/3/22 22:39, Chris Angelico wrote: > On Mon, 4 Apr 2022 at 14:22, Brian McCall wrote: >> Related to these questions, there is the question of what to do about mixed systems? > Should 2.54 in / 1 cm evaluate to 2.54 in/cm or should it evaluate to 1? > > I would say that 2.54in/1cm should be equal to 1. Units should > completely cancel out. It seems like the point of this exercise is to *not* have units cancel out -- at least, not unnecessarily. 2.54in / 1 cm should be 2.54in/cm, otherwise multiplying by 5 kelvin will be one of those hard-to-find bugs. Of course, it's actually 2.54cm/in. -- ~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/GBMXCK6EMNPXGEYMH3IZVRSAAH7GINVB/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Native support for units [was: custom literals]
On 4/4/22 08:54, Ken Kundert wrote: > Now consider the issue of “unitless units”. In electrical circuit we often talk > about gain, which it the ratio between the signal level at the output of > a circuit relative to the signal level at the input. But you need to be > specific about how you measure signal level. Typically, it would be a voltage, > current, or power level. Consider a circuit where both the input and output are > measured in volts. Then the gain would have units of "V/V", which is unitless > in dimensional analysis. But units of "V/V" (voltage gain) is much different > from units of "A/A" (current gain) or "W/W" (power gain), even though they have > the same dimensions. Mixing them up results in errors and confusion. An > additional complication is that sometimes logarithmic units are used. For > example, decibels in voltage, or dBV, is 20*log(Vout/Vin). Again, > a dimensionless quantity, but nonetheless "dBV" much different from "V/V". [several other examples elided] It seems to me that these "unitless' units actually have units, even if they *appear* to cancel each other out. -- ~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/XLRERZPX4WP7S4D4WZ7DB3XSKICQJLDX/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Native support for units [was: custom literals]
On 4/3/22 11:52, Brian McCall wrote: > If you had asked me twenty years ago if I thought units should be a native part of any > programming language, I would have said absolutely - because in my youthful ignorance > I had no idea what it would take to make such a thing work. Five years later, I would > have said "not worth it". Now I'm back where I started. The lack of native language > support for SI units is a problem for an entire segment of programmers. Programming > languages took a big step forward in deciding that EVERYTHING is a pointer/reference, > and EVERYTHING is an object. They need to take another step forward to say that EVERY > number has a unit, including "unitless". Not having this language feature is becoming > (or already is) a problem. The question is, is it Python's problem? On 4/3/22 14:20, Ricky Teachey wrote: > The libraries out there- pint is probably the biggest one- have filled those gap as much as they can, but there are so > many shortfalls... > > The old engineering disciplines- mine (civil engineering), structural, electrical, etc- are the next frontier in the > "software eats the world" revolution, and they desperately need a language with native units support. I was just on an > interview call yesterday for a senior engineer role at a large multinational earth works engineering firm and we spent > 15 minutes talking about software and what we see coming down the road when it comes to the need for our discipline to > grow in its software creation capabilities. > > Python SHOULD be that language we do this with. It is awesome in every other way. But if it isn't DEAD SIMPLE to use > units in python, it won't happen. Well, if we're spit-balling ideas, what about: 63_lbs or 77_km/hr ? Variables cannot start with a number, so there'd be no ambiguity there; we started allowing underbars for separating digits a few versions ago, so there is some precedent. We could use the asterisk, although I find the underbar easeir to read. Mechanically, are `lbs`, `km`, `hr`, etc., something that is imported, or are they tags attached to the numbers? If attached to the numbers, memory size would increase and performance might decrease -- but, how often do we have a number that is truly without a unit? How old are you? 35 years How much do you weigh? 300 kg What temperature do you cook bread at? 350 F -- ~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/JDYXM3AH3ESOL7L6ALPRZOOURL3ZLRHP/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Anonymous namedtuples, revisited
On 3/29/22 14:41, Christopher Barker wrote: > Ethan Furman queried: >> The `__dict__` is needed to store the field names -- did you add `__dict__` to the >> `__slots__`? > > Nope — though the error indicated that I couldn’t add anything to __slots__ when subclassing tuple. But I may have > misunderstood the error. Ah, that's right -- it's saying that *instances* cannot have anything in `__slots__`, but the class can still have fields: >>> class Tuple(tuple): ... this = 'eggs' ... that = 'spam' ... __slots__ = () ... def __new__(cls, *args): ... return tuple.__new__(cls, *args) ... >>> t = Tuple((1,)) >>> t (1,) >>> t.this 'eggs' >>> t.that 'spam' So the Tuple class would have properties that redirect to the correct offset -- but that would require a different tuple class for each field configuration. -- ~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/IHOJQLM5KZIKC6TNKZCYHQ25MICBIIW5/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Anonymous namedtuples, revisited
On 3/29/22 09:57, Ricky Teachey wrote: > On Tue, Mar 29, 2022 at 12:49 PM Ethan Furman wrote: >> The `__dict__` is needed to store the field names -- did you add `__dict__` to the >> `__slots__`? (Of course, if you've added `__dict__` then you lose the limited size >> of `__slots__`.) > > Maybe I'm being an ignoramus but: how would it be possible to even use slots? Slots > are descriptors living in the class namespace. You don't know ahead of time what the > member names are, so you can't use slots, right? You can use them, just make sure one of the slots is `__dict__`. Of course, by adding `__dict__` you lose most (all?) of the advantages of using `__slots__` in the first place. -- ~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/QM7MIHKP2GSBN6TYMPDIFKGHGC7KEH6E/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Anonymous namedtuples, revisited
On 3/29/22 09:14, Christopher Barker wrote: > [...] I tried to use __slots__ in TupleWithNames, but apparently you can't use __slots__ in a > tuple subclass ('cause tuple's already using it ??) -- but that could be done in a builtin. > then it wouldn't need a __dict__ The `__dict__` is needed to store the field names -- did you add `__dict__` to the `__slots__`? (Of course, if you've added `__dict__` then you lose the limited size of `__slots__`.) -- ~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/B3JZKXQ4HDW5IRNMYKDKB5QFGHRR42AH/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: mro and super don't feel so pythonic
On 3/26/22 12:04, Ethan Furman wrote: > On 3/26/22 09:57, malmiteria wrote: > >> The core of what i wanna discuss here is that i don't think mro and super (mainly because it >> relies on mro) are very pythonic. Mainly that some behaviors of the mro are too implicit, and >> are silencing what really should be errors. > > [...] In other words, subclassing is a very tight coupling of code, and you had better know > the classes you are inheriting from to get it right -- and that part is the programmer's > responsibility, not Python's. To add to that, you can write your custom metaclass, or even (and more easily) a class decorator, that goes through the mro and raises an exception if there are any duplicate methods in previous classes that have not been overridden in the new class. -- ~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/VIWNDPEHPD2BO7S7YHQTPPK2QBOPQH5Z/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: mro and super don't feel so pythonic
On 3/26/22 09:57, malmiteria wrote: > The core of what i wanna discuss here is that i don't think mro and super (mainly because it relies on mro) are very pythonic. Mainly that some behaviors of the mro are too implicit, and are silencing what really should be errors. When I first started using Python I also didn't like super() and the mro. However, at some point it dawned on me that subclassing is not a trivial task -- you don't just get a new class with some neat behavior from another class -- what you get is the original class, plus some neat behavior from the new class. In other words, subclassing is a very tight coupling of code, and you had better know the classes you are inheriting from to get it right -- and that part is the programmer's responsibility, not Python's. To use your `run()` example: class A: def run(self): print('A') class B: def run(self): print('B') class Z(A, B): def run(self): # make the programmer choose raise RuntimeError("call to `run()` not allowed, choose `run_a()` or `run_b()`") def run_a(self): return A.run() def run_b(self): return B.run() -- ~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/EVCUL3PVRIDAMMRYGU56J4AK4ZBRNM64/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: [Python-Dev] An unambiguous way of initializing an empty dictionary and set
On 3/13/22 14:49, joao.p.f.batista...@gmail.com wrote: > Currently: > l = [] # new empty list > t = () # new empty tuple > s = set() # new empty set (no clean and consistent way of initializing regarding the others) <<< > d = {} # new empty dictionary > > Possible solution: > s = {} # new empty set > d = {:} # new empty dictionary (the ":" is a reference to key-value pairs) > > Current workaround at least for consistency: > l = list() # new empty list > t = tuple() # new empty tuple > s = set() # new empty set > d = dict() # new empty dictionary > > However, it doesn't feel right to not be able to initialize an empty set as cleanly and > consistently as lists, tuples and dictionaries in both forms. This is a topic better fit to python-ideas. -- ~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/AHUHYKKSVXSAIVYVAMNZDLFJQI4BEJU5/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: New Web Interface Library For Python?
On 2/8/22 2:08 PM, Abdur-Rahmaan Janhangeer wrote: > It might be true that the days of batteries included are over, They are not. Batteries are still included in Python, and more advanced versions of built-in batteries are available elsewhere. -- ~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/TUWF3AG4DPDBLTW2SV7IQMEJ3Y42DZIP/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Limit scope of variables using round brackets
On 1/17/22 7:33 AM, John Sturdy wrote: > One of the few things I don't like about Python is that variable scope continues after > the end of the suite the variable was created in --- probably because I think of local > variable declarations as equivalent to lambdas that are called immediately, which works > for most modern programming languages as well as for the theory. For example, it bugs > me that you can write: > > if a: > b = f(x) > else: > b = g(y) > > and get the same variable 'b' from it in the lines of code following that, regardless > of which path was taken. That's a feature, not a bug. A very common Python pattern is to set such common variables using if/else or try/except, and then to use those variables further along in the code *outside* the suite that set them. > I think a way to address this that would be more compatible with Python's style would > be to add a new declaration syntax, perhaps borrowing from other languages and using > the keyword 'let' where the variable is first assigned (and the rest of the assignment > / declaration being as before). The variables declared this way would exist up to the > end of the suite in which they were declared; The syntax might be optional, but the change in semantics is not. If that change was made, then every Python programmer would have to keep track of which variables were created with `let` and then also track the lifespan of those variables which are now different from other variables in that same function or class scope. I'm sorry if programming in Python is not a choice you get to make, but that change is a huge jump in complexity for a near-zero gain. -- ~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/CX6RLKSK6I5J3XYHFU2G4RP3IPIXEK5G/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] staticmethod vs classmethod [was: Add a decorators called @staticproperty]
On 12/19/21 5:40 AM, Serhiy Storchaka wrote: > classmethod supersedes staticmethod. It was not clearly known when they > were introduced, but now we see that there is very few use cases for > staticmethod which cannot be replaced by classmethod (actually only one > specific case). What is the one case? -- ~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/MQUOJUMWEDG5B3J3H3UAD5ULFZCWLI3L/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Add a decorators called @staticproperty
By way of correcting misconceptions: On 12/18/21 8:39 AM, Chris Angelico wrote: > > I'm not sure that this is actually possible the way you're doing it. > The descriptor protocol (which is what makes properties work) won't > apply when you're looking up statically. On 12/18/21 9:19 AM, Christopher Barker wrote: > > Anyway, the thing is that both staticmethod and property are implimented using descriptors, which I think can only be > invoked by instance attribute lookup. That is, the class attribute IS a descriptor instance. While it is true that a descriptor does not get the chance to run its `__set__` and `__delete__` methods when called on the class, it does get to run its `__get__` method. In code: class descriptor_example: # def __get__(self, instance, owner=None): if owner is not None: print('called directly from the class, have a cookie!') return 'chocolate-chip cookie' # def __set__(self, instance, value): # never called from the class raise TypeError # def __delete__(self, instance, value): # never called from the class raise TypeError class Test: huh = descriptor_example() >>> Test.huh called directly from the class, have a cookie! chocolate-chip cookie >>> Test.huh = 7 # change `huh` >>> Test.huh 7 >>> Test.huh = descriptor_example() # put it back >>> Test.huh called directly from the class, have a cookie! chocolate-chip cookie >>> del Test.huh # remove huh >>> Test.huh AttributeError Having said that, I don't think it's needs direct support in the stdlib. -- ~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/CEJJBFG27RI3DQ6H5XJB6TBYGF57BONC/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: PEP 671 (late-bound arg defaults), next round of discussion!
On 11/30/21 10:16 PM, Chris Angelico wrote: > *PEP 671: Syntax for late-bound function argument defaults* > > Questions, for you all: > > 1) If this feature existed in Python 3.11 exactly as described, would > you use it? No. > 2) Independently: Is the syntactic distinction between "=" and "=>" a > cognitive burden? Yes. > 3) If "yes" to question 1, would you use it for any/all of (a) mutable > defaults, (b) referencing things that might have changed, (c) > referencing other arguments, (d) something else? a, b, c > 4) If "no" to question 1, is there some other spelling or other small > change that WOULD mean you would use it? (Some examples in the PEP.) Have the token/keyword be at the beginning instead of in the middle. -- ~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/HEC53APMOJA4WR5QTF7Y2VSKWQE62JHU/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Adding pep-8-casing-compliant aliases for unittest and logging
On 11/11/21 9:35 PM, Christopher Barker wrote: > Matt del Valle wrote: >> So perhaps we could narrow the scope of this down to just adding snake_case aliases to the logging and >> unittest modules [...] > > The reason those are spelled that way is because they are ported from Java. > > And IMHO that “Java flavor” is a bigger issue than just the names. It’s the whole structure. So if we’re > going to touch those, let’s make a Pythonic API, with PEP 8 compliant names, instead :-) Besides the names, what are the issues? And are those issues covered by pytest, etc? unittest is the first (and only) testing framework I have ever used, so any info is appreciated. -- ~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/5SX3FO4OVPWGOH6C2E32PNX5YOBAAXMJ/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] [Python-Dev] Adding pep-8-casing-compliant aliases for unittest and logging
On 11/11/21 11:53 AM, Matt del Valle wrote: Okay, so from the replies so far it looks like this is very quickly going into the 'never gonna happen' dumpster, so in the interests of salvaging *something* out of it: [...] I just dislike having to settle for 'it's what we've got'. With these two modules in particular, a lot of the arguments that have been made so far either don't apply or are not as strong (such as the confusion of having builtins.list, builtins.List and typing.List). Additionally, these are significantly more ancillary portions of the stdlib than the builtins, much less likely to cause as severe of a disruption (I personally don't believe a backward-compatible change like this which only adds aliases would be as disruptive as many people claim, but concede that that's subjective), and much less likely to have the implementation change so drastically as to want to change out types for factory functions or vice-versa. So perhaps we could narrow the scope of this down to just adding snake_case aliases to the logging and unittest modules [...] +1 I would happily change all my unittest and logging usage to snake case if those aliases existed. -- ~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/JZVMZDG4NBUWLMFHHV3DBTTVDSSLWBYT/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Adding pep8-casing-compliant aliases for the entire stdlib
I think what Paul is referring to is that according to PEP 8: - functions: Function names should be lowercase, with words separated by underscores as necessary to improve readability. - types: Class names should normally use the CapWords convention. And, of course: - Names that are visible to the user as public parts of the API should follow conventions that reflect usage rather than implementation. So, given those three items, should `str` be `str` because it is used often as a function, or should it be `Str` because it is often subclassed? -- ~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/PD5FIL4UM7MYASYMG6DD6BKONBFDZDGV/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: PEP 671: Syntax for late-bound function argument defaults
On 11/3/21 2:31 PM, Chris Angelico wrote: > On Thu, Nov 4, 2021 at 5:54 AM Ethan Furman wrote: >> On 11/3/21 12:13 AM, Chris Angelico wrote: >>> Python has a strong policy of evaluating things immediately, or being >>> very clear about when they will be evaluated >> >> Putting the marker in the middle of the name binding expression is not "very clear" -- particularly >> since the advice is "no spaces around '=' in function headers and calls". [typo above fixed: 'ne' -> 'no' > Not sure what you mean, I mean the same thing that D'Aprano has reiterated several times: def do_something_fun(target:Any, action:int=-1, permissions:int=>target.perm): pass vs def do_something_fun(target:Any, action:int=-1, @permissions:int=target.perm): pass Having the `@` in front instead of buried in the middle is clear, and just like the * and ** in `*args` and `**kwds` signals that those are different types of variables, the @ in `@permissions` signals that `permissions` is a different kind of variable -- and yes, the fact that it is late-bound does make it different; to claim otherwise is akin to claiming that `args` and `kwds` aren't different because in the end they are just names bound to objects. > [snip javascript example] Is your javascript example trying to show that putting the sigil in front is nonsensical? If no, then what? If yes, then it is plain that you and I simply disagree and neither of us is going to convince the other. -- ~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/2KPVUNE3SMDOKH2J37NHKB6PWPYUQTQP/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Beginners accidentally shadow module names due to different expectation of the resolution order for module imports
On 11/3/21 12:21 PM, Florian Wetschoreck wrote: > In order to prevent confusion, I want to point out that the primary scenario that I meant is not that the file imports > itself but another file in the same directory with the name of a module that is also installed in site-packages. Not > sure if I made that clear in my original post? Maybe if the module-level AttributeError included the complete path/filename of the module? It would then be much more easily discernible that the imported "pandas" is not the correct one. -- ~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/VRMR2NQ2ZAEMFTV5ARPH5KYY4H6XLKGF/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: PEP 671: Syntax for late-bound function argument defaults
On 11/3/21 12:13 AM, Chris Angelico wrote: > Python has a strong policy of evaluating things immediately, or being > very clear about when they will be evaluated Putting the marker in the middle of the name binding expression is not "very clear" -- particularly since the advice is "ne spaces around '=' in function headers and calls". -- ~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/IPNN7HL54LBE23AKYXQSYML52F4MOETZ/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: PEP 671: Syntax for late-bound function argument defaults -- choice of -> vs @
On 11/3/21 10:35 AM, Steven D'Aprano wrote: > I suppose that we could even add yet another overloaded meaning on the > asterix: > > # with no default, * keeps the old meaning of collecting > # extra positional values > > *parameter > > # with a default, * triggers late-binding > > *parameter=expression > > I should hate that, I know I should... but I kinda don't. Don't worry, I do. ;-) -- ~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/C675R5WABWBHT3O7GZH7HR4736SKY7HO/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: PEP 671: Syntax for late-bound function argument defaults -- choice of -> vs @
On 11/3/21 9:07 AM, Chris Angelico wrote: > On Thu, Nov 4, 2021 at 2:29 AM Ethan Furman wrote: >> One similarity that I don't think has been mentioned yet: >> >> - decorator syntax says, "run me later, after this function is built" >> >> - late-bound argument syntax says, "run me later, just before each function call" > > Hmm, I more think of decorator syntax as "modify this function". It > runs at the same time that the def statement does, although the > effects may be felt at call time (including a lot of simple ones like > lru_cache). Well, if "at the same time" you mean "after the function is defined even though the decorator appears first", then sure. ;-) >> Because both mean "run me later" we can leverage the @ symbol to aid understanding; also, >> because "run me later" can completely change the workings of a function (mutable defaults, >> anyone?), it deserves more attention than being buried in the middle of the expression where >> it is easy to miss (which is why I originally proposed the ? -- it stood out better). > > One of the reasons I want to keep the latebound vs earlybound > indication at the equals sign is the presence of annotations. I want > to associate the lateboundness of the default with the default itself; I think that level of specificity is unnecessary, and counter-productive. When discussing a particular late-bound default, how are you (usually) going to reference it? By name: "the 'spam' parameter is late-bound" -- so decorate the variable name. > So if you want to make use of the at sign, it would end up looking like matrix multiplication: > > def func(spam: list @= []) -> str: ... > def func(spam: list =@ []) -> str: ... > > rather than feeling like decorating the variable. Which is horrible. Put the @ at the front: - its relation to decorators, and delayed evaluation, is much more clear - it stands out better to the reader -- ~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/PG37EY2GKTQ2HZKOG6XLUTTNSJW7XFE5/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: PEP 671: Syntax for late-bound function argument defaults -- choice of -> vs @
One similarity that I don't think has been mentioned yet: - decorator syntax says, "run me later, after this function is built" - late-bound argument syntax says, "run me later, just before each function call" Because both mean "run me later" we can leverage the @ symbol to aid understanding; also, because "run me later" can completely change the workings of a function (mutable defaults, anyone?), it deserves more attention than being buried in the middle of the expression where it is easy to miss (which is why I originally proposed the ? -- it stood out better). -- ~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/VUKFDNJBHSM7GJLKRDJHGQ7WKZZDLB2F/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: PEP 671: Syntax for late-bound function argument defaults
On 10/23/21 5:13 PM, Chris Angelico wrote: > PEP: 671 > Title: Syntax for late-bound function argument defaults I have a major concern about the utility of this addition -- it was mentioned already (sorry, I don't remember who) and I don't think it has yet been addressed. Using the `bisect()` function as a stand-in for the 20+ years worth of Python APIs in existence: def bisect_right(a, x, lo=0, hi=None, *, key=None): if hi is None: hi = len(a) while lo < hi: ... That function would be transformed to: def bisect_right(a, x, lo=0, @hi=len(a), *, key=None): if hi is None: hi = len(a) while lo < hi: ... Notice that the `None` check is still in the body -- why? Backwards compatibility: there is code out there that actually passes in `None` for `hi`, and removing the None-check in the body will suddenly cause TypeErrors. This seems like a lot of effort for a very marginal gain. -- ~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/VGCI7N3NHB4HBPKFBV2DWTJSJBRT3SGV/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: PEP 671: Syntax for late-bound function argument defaults
On 10/26/21 12:08 PM, Ricky Teachey wrote: > On Tue, Oct 26, 2021 at 2:40 PM Chris Angelico wrote: >> Do you have any examples where this isn't the case? > > I don't. I only have a niggling feeling that maybe this is a bigger problem than > we're giving it credit for. > > At bottom I guess I'd describe the problem this way: with most APIs, there is a way > to PASS SOMETHING that says "give me the default". With this proposed API, we don't > have that; the only want to say "give me the default" is to NOT pass something. > > I don't KNOW if that's a problem, it just feels like one. Several times I've had to write code that calls a function in several different ways, based solely on where I could pass None to get the default behavior: my_wrapper_func(this, that, the_other=None): if framework.version > 4: framework.utility(this, that, the_other) elif framework.version > 3.5: if the_other is None: framework.utility(this, that) else: framework.utility(this, that, the_other) What a pain. When this PEP originally came out I thought that passing None was the way to trigger it -- if that's not the case, and there is nothing we can pass to trigger it, I am much less interested. -- ~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/YBRFL4XISDGXKCVXTBR4WVS3UJWP4DRR/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: PEP 671: Syntax for late-bound function argument defaults
On 10/25/21 11:50 AM, Erik Demaine wrote: > Here's another example where it matters whether the default expressions are computed within their own scope: > > ``` > def f(x := (y := 5)): > print(x) # 5 > print(y) # 5??? > f() > ``` That should definitely be a SyntaxError. -- ~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/KO2C3TVTXCGOVRROI44VRZQAX4QRECTX/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: PEP 671: Syntax for late-bound function argument defaults
On 10/25/21 6:54 AM, Eric V. Smith wrote: > On 10/25/2021 8:26 AM, Chris Angelico wrote: >> If it's done with syntax, it can have special behaviour. If it looks >> like a function call (or class constructor), it doesn't look like it >> has special behaviour. > > This has been mentioned before, but I'll say it again: It doesn't need to be syntax in the sense of non-ascii > characters, it could be a (soft) keyword: > > def process_files(processor, files=deferred os.listdir(DEFAULT_DIR)): I agree. My two favorite bike-shed colors are - `deferred` soft keyword - @ in the front Both options make it much clearer that something special is happening, whilst all of the in-the-middle options can be easily missed. -- ~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/BSEBMA7GZRIJEBC2Q5MIJBOFAWSD4QPU/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: PEP 671: Syntax for late-bound function argument defaults
On 10/24/21 11:22 PM, Steven D'Aprano wrote: > On Sun, Oct 24, 2021 at 05:40:55PM +0100, Jonathan Fine wrote: >> def puzzle(*, a=>b+1, b=>a+1): >> return a, b > We can consider that to be syntactic sugar for: > > def puzzle(*, a=None, b=None): > if a is None: > a = b+1 > if b is None: > b = a+1 > > So that has a perfectly sensible interpretation: > > - a is optional > - b is optional > - but you must supply at least one. > > and should be perfectly legal. I see no reason to prohibit it. > > (It would be nice if we could give a better exception, rather than just > UnboundLocalError, but that's not essential.) +1 ___ 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/MAUVXBGGSIEW4UGZMUECBVXXY5CZGEQU/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Syntax for late-bound arguments
On 10/23/21 8:04 PM, Bruce Leban wrote: > I was talking about (2) but I should have been explicit. And yes, you highlight a potential source of confusion. > > def f(x=>x + 1): ... > > means that x is 1 more than the value of x from the enclosing global scope (at function call time) while Uh, no, that is a SyntaxError (or should be) -- a delayed variable cannot reference itself. -- ~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/U3WGHQLFPWNN6MVA5BF2FKIKOYNZNEXQ/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Syntax for late-bound arguments
On 10/23/21 2:23 PM, Chris Angelico wrote: > It seems like there's broad interest in this, but a lot of details to > nut out. I think it may be time for me to write up a full PEP. Guido, > if I'm understanding recent SC decisions correctly, a PEP editor can > self-sponsor, correct? Of all people, PEP editor or not, you should be able to self-sponsor. ;-) But if you need one, I'm happy to step up. -- ~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/LC6TOTPNPWJAM7SVGDUE5VEAUFNBTF6Y/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Syntax for late-bound arguments
On 10/23/21 9:44 AM, Chris Angelico wrote: > Feel free to propose an improvement to the syntax. Whatever spelling > is ultimately used, this would still be of value. def bisect(a, x, lo=0, hi?=len(a)): -- ~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/HHAD2XUPIIERWOK5CU3MTTSDGWWBVJ7P/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Syntax for late-bound arguments
On 10/23/21 9:07 AM, Chris Angelico wrote: > Proposal: Proper syntax and support for late-bound argument defaults. I like the proposal. > def spaminate(thing, count=:thing.getdefault()): > ... > > def bisect(a, x, lo=0, hi=:len(a)): > if lo < 0: > raise ValueError('lo must be non-negative') But not the color -- I see "=:" too easily confused with ":=". However, I do like: -- ~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/ZEN4ZGBSMDCUW5JT5LLD45NKQIQDC5UT/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Real Positional Arguments or OO Currying
On 10/18/21 3:20 AM, Mathew Elman wrote: > I don't know if this has been suggested before, or if this is outlandishly impossible > (though I would be surprised if it was), so apologies in advance if so. > > I have on occasion come across a situation where I use/write a signature like this: > > def insert_x_into_y(x, y): Ugh, that is horrible. > or worse > > def insert_into(item, container): > ... Actually, that looks fine -- the previous example was too verbose. > where, despite a driving idea of python syntax being [readable] in english, the function > signature is distinctly not english. Where did you get that idea? "executable psuedo-code" is a far cry from English. > What would be really cool, is if python let you write function signatures like this: > > def insert_(item)_into_(container): > ... > > where the arguments dispersed between the function name are positional only argument, > and any key word arguments would have to go at the end. It would create a function > that could be called as: > > insert_(1)_into_(my_list) Why wouldn't you just use `my_list.insert(1) ? > This sort of signature is particularly annoying for boolean checks like `isinstance` (N.B. I am _not_ suggesting changing any builtins), which one could wrap with: > > def is_(obj)_an_instance_of_(type): > return isinstance(obj, type) Sorry, way too verbose for me. It is definitely possible to be *too* explicit. While I agree it would be cool (and having written what I thought were some pretty cool things, like not needing to include the value for an enum member), in practice cool and get quite irritating. -- ~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/SSAXYRPTQXB33JIIBVZAVYROZMLLYJ22/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Real Positional Arguments or OO Currying
On 10/18/21 6:29 AM, Mathew Elman wrote: >> What you are describing is very, very dissimilar to currying. It's simply multi-argument > functions with a different call syntax. > > It is almost identical to currying, the only differences are: > 1. the intermediate return being an object with an attribute (rather than a new function) >that you call. > 2. the names of the attributes from 1 (which aren't a thing otherwise) are declared when >defining the initial function Citations, please? It's your idea, so it's on you to come up with supporting evidence. >> It's not even close to worthwhile to have special syntax for rare cases. > > It would make sense for a huge number of functions, its just not a natural way to consider > writing them because the syntax doesn't exist e.g. almost any boolean function makes sense > this way. Again, a example list of functions would help -- if there are truly a huge number of them then giving us 10 to 20 shouldn't be hard. -- ~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/GGJZSO2FT5LBU4AVE2AGPJTPQ6E7SOMU/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Real Positional Arguments or OO Currying
On 10/18/21 6:23 AM, Mathew Elman wrote: > When learning python, and even sometimes now, I have had to look at the implementation of a function in order to recall which order arguments should go. Seems like the docs should cover that (or even `help()`) -- and if not, then the parameter names could be better. -- ~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/M2JIQADNJFP7V2VEFNQOH3VK2DQMZCC3/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] PEP 663: Improving and Standardizing Enum str(), repr(), and format() behaviors
PEP 663 is presented below for your viewing pleasure. Comments, questions, and concerns are welcome. PEP: 663 Title: Improving and Standardizing Enum str(), repr(), and format() behaviors Version: $Revision$ Last-Modified: $Date$ Author: Ethan Furman Discussions-To: python-...@python.org Status: Draft Type: Informational Content-Type: text/x-rst Created: 23-Feb-2013 Python-Version: 3.11 Post-History: 20-Jul-2021 10-Sep-2021 Resolution: Abstract Now that we have a few years experience with Enum usage it is time to update the ``repr()``, ``str()``, and ``format()`` of the various enumerations by their intended purpose. Motivation == The addition of ``StrEnum`` with its requirement to have its ``str()`` be its ``value`` is inconsistent with other provided Enum's ``str``. Having the ``str()`` of ``IntEnum`` and ``IntFlag`` not be the value causes bugs and extra work when replacing existing constants. Having the ``str()`` and ``format()`` of an enum member be different can be confusing. The iteration of ``Flag`` members, which directly affects their ``repr()``, is inelegant at best, and buggy at worst. Rationale = Enums are becoming more common in the standard library; being able to recognize enum members by their ``repr()``, and having that ``repr()`` be easy to parse, is useful and can save time and effort in understanding and debugging code. However, the enums with mixed-in data types (``IntEnum``, ``IntFlag``, and the new ``StrEnum``) need to be more backwards compatible with the constants they are replacing -- specifically, ``str(replacement_enum_member) == str(original_constant)`` should be true (and the same for ``format()``). IntEnum, IntFlag, and StrEnum should be as close to a drop-in replacement of existing integer and string constants as is possible. Towards that goal, the str() output of each should be its inherent value; e.g. if ``Color`` is an ``IntEnum``:: >>> Color.RED >>> str(Color.RED) '1' >>> format(Color.RED) '1' Note that format() already produces the correct output in 3.10, only str() needs updating. As much as possible, the ``str()`, ``repr()``, and ``format()`` of enum members should be standardized across the stardard library. The repr() of Flag currently includes aliases, which it should not; fixing that will, of course, already change its ``repr()`` in certain cases. Specification = There a three broad categories of enum usage: - standard: Enum or Flag a new enum class is created, and the members are used as ``class.member_name`` - drop-in replacement: IntEnum, IntFlag, StrEnum a new enum class is created which also subclasses ``int`` or ``str`` and uses ``int.__str__`` or ``str.__str__``; the ``repr`` can be changed by using the ``global_enum`` decorator - user-mixed enums and flags the user creates their own integer-, float-, str-, whatever-enums instead of using enum.IntEnum, etc. Some sample enums:: # module: tools.py class Hue(Enum): # or IntEnum LIGHT = -1 NORMAL = 0 DARK = +1 class Color(Flag): # or IntFlag RED = 1 GREEN = 2 BLUE = 4 class Grey(int, Enum): # or (int, Flag) BLACK = 0 WHITE = 1 Using the above enumerations, the following table shows the old and new behavior, while the last shows the final result: +-+--+-++---+---++---+ | type | enum repr() | enum str() | enum format() | flag repr() | flag str() | flag format() | +-+--+-++---+---++---+ | standard| 3.10 | || | | Color.RED|GREEN| Color.RED|GREEN | | +--+-++---+---++---+ | | new | || | | Color.RED|Color.GREEN | Color.RED|Color.GREEN | +-+--+-++---+---++---+ +-+--+-++---+---++---+ | user mixed | 3.10 | || 1 || | 1 | | +--+-++---+---++---+ | |
[Python-ideas] Re: Iterate through members of enum.Flag
On 9/10/21 4:19 AM, matt...@matthewstocks.co.uk wrote: > My proposal is that iterating through a member of a Flag enum will return all the constituent members. It's a good proposal, and is already in 3.11. If you want the functionality now you can use the aenum [0] library. -- ~Ethan~ [0] https://pypi.org/project/aenum/ ___ 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/E26WSI2R7EGYJMLGZC2DA2J2KBND2LXC/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Queue and bool() -- an oversight? [was: We should have an explicit concept of emptiness for collections]
On 8/24/21 10:26 PM, Guido van Rossum wrote: > On Tue, Aug 24, 2021 at 22:19 Christopher Barker wrote: >> On Tue, Aug 24, 2021 at 9:58 PM David Mertz, Ph.D. wrote: >>> Sorry, I should have been more explicit. The several kinds of queues can all >>> "contain" items, but do not respond to len(). >> >> yeah, I should have looked more closely at your list >> >> Though i would consider that an oversight, len(a_queue) could be handy. >> >> There is qsize() -- I wonder if there's a reason not to have __len__ do the same >> thing -- O(n) maybe? See Guido's point that there's an assumption tha len() will >> be O(1). > > What sort of code would be able to do anything useful with either a sequence or > a queue? Queues aren’t iterable. This seems a case of hyper-generalization. I don't think it's hyper-generalization of queues and sequences, but rather being consistent with the idea of something vs nothing. We can't iterate over integers, but not-zero numbers are still truthy. -- ~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/UAU4JGKER6QXSZDDDEPOJTOIVTNCSXVB/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: We should have an explicit concept of emptiness for collections
On 8/24/21 4:35 PM, Cameron Simpson wrote: > If we're chasing rough edges, consider queue.Queue: > > >>> from queue import Queue > >>> Q = Queue() > >>> Q.empty() > True > >>> if Q: print("Q is true") > ... > Q is true > > I would often like to treat Queues as a container of queued items, > basicly because I'd like to be able to probe for the presence of queued > items via the emptiness idiom. But I can't. It does has a .empty() > method. > > I don't even know what my point is here :-( Perhaps that's it's irritating when containers redefine something vs nothing? ;-) -- ~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/D2SKQUA2BLY7VNM5PEWGSHQQXM3ORTRJ/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: We should have an explicit concept of emptiness for collections
On 8/24/21 3:03 PM, Tim Hoffmann via Python-ideas wrote: > **How do you check if a container is empty?** > > IMHO the answer should not depend on the container. I think this is the fly in the ointment -- just about everything, from len() to bool(), to add, to iter() /all/ depend on the container -- even equality depends on the container. `and`, `or`, and `not` partially depend on the container (via bool()). Only `is` is truly independent. > Not a solution: > 0) The current `if not seq` syntax. "check Falsiness instead of emptiness" is a > simplification, which is not always possible. > > Possible solutions: > > 1) Always use `if len(seq) == 0`. I think, this would works. But would we want to >write that in PEP-8 instead of `if not seq`? To me, this feels a bit too low level. > > 2) A protocol would formalize that concept by building respective syntax into the >language. But I concede that it may be overkill. > > 3) The simple solution would be to add `is_empty()` methods to all stdlib containers >and encourage third party libs to adopt that convention as well. That would give a >uniform syntax by convention. > > Reflecting the discussion in this thread, I now favor variant 3). And since (3) is a method on the container, it absolutely "depends on the container". -- ~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/O2QZMKYC6FLKADYKS4UPCINPKJ65DCZV/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: We should have an explicit concept of emptiness for collections
On 8/23/21 2:31 PM, Tim Hoffmann via Python-ideas wrote: > Ethan Furman wrote: >> It seems to me that the appropriate fix is for numpy to have an "is_empty()" function >> that knows how to deal with arrays and array-like structures, not force every container >> to grow a new method. > > Yes, numpy could and probably should have an "is_empty()" method. However, defining a > method downstream breaks duck typing and maybe even more important authors have to > mentally switch between the two empty-check variants `if users` and `if users.is_empty()` > depending on the context. The context being whether or not you working with numpy? Is there generic code that works with both numpy arrays and other non-numpy data? Do we have any non-numpy examples of this problem? >>> If you want to write a function that accepts array-like `values`, you have to change >>> a check `if values` to `if len(values) == 0`. That works for both but is against the >>> PEP8 recommendation. This is a shortcoming of the language. >> >> Numpy is not Python, but a specialist third-party package that has made specialist >> choices about basic operations -- that does not sound like a shortcoming of the language. > > The "specialist choices" ``if len(values) == 0` in Numpy are the best you can do within > the capabilities of the Python language if you want the code to function with lists and > arrays. For Numpy to do better Python would need to either provide the above mentioned > "has element-wise operations" protocol or an is_empty protocol. > > I consider emptiness-check a basic concept that should be consistent and easy to use across containers. Python has an emptiness-check and numpy chose to repurpose it -- that is not Python's problem nor a shortcoming in Python. Suppose we add an `.is_empty()` method, and five years down the road another library repurposes that method, that other library then becomes popular, and we then have two "emptiness" checks that are no longer consistent -- do we then add a third? -- ~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/AWF4KLCNQ3AJX2SHEGTW6JFCMM7A2AXM/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: We should have an explicit concept of emptiness for collections
On 8/23/21 2:06 PM, Tim Hoffmann via Python-ideas wrote: > On a technical level, everything can be solved with the current language capabilities. The > main advantage is clearer semantics (explicit is better / readability counts) Note the explicit and readability are often at odds with each other. -- ~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/3KUWUJ53T2HMRETE7XKABQBCXGKNEKMK/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: We should have an explicit concept of emptiness for collections
On 8/23/21 1:15 PM, Tim Hoffmann via Python-ideas wrote: > If you want to write a function that accepts array-like `values`, you have to change > a check `if values` to `if len(values) == 0`. That works for both but is against the > PEP8 recommendation. This is a shortcoming of the language. Numpy is not Python, but a specialist third-party package that has made specialist choices about basic operations -- that does not sound like a shortcoming of the language. It seems to me that the appropriate fix is for numpy to have an "is_empty()" function that knows how to deal with arrays and array-like structures, not force every container to grow a new method. -- ~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/IHCXG7X5YPJWPRVZVXR3RGCCN43UV7MC/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] RFC for PEP 663: Improving and Standardizing Enum str(), repr(), and format() behaviors
PEP: 663 Title: Improving and Standardizing Enum str(), repr(), and format() behaviors Version: $Revision$ Last-Modified: $Date$ Author: Ethan Furman Discussions-To: python-...@python.org Status: Draft Type: Informational Content-Type: text/x-rst Created: 23-Feb-2013 Python-Version: 3.11 Post-History: 20-Jul-2021 Resolution: Abstract Now that we have a few years experience with Enum usage it is time to update the ``repr()``, ``str()``, and ``format()`` of the various enumerations by their intended purpose. Motivation == The addition of ``StrEnum`` with its requirement to have its ``str()`` be its ``value`` is inconsistent with other provided Enum's ``str``. Having the ``str()`` of ``IntEnum`` and ``IntFlag`` not be the value causes bugs and extra work when replacing existing constants. Having the ``str()`` and ``format()`` of an enum member be different can be confusing. The iteration of ``Flag`` members, which directly affects their ``repr()``, is inelegant at best, and buggy at worst. Rationale = Enums are becoming more common in the standard library; being able to recognize enum members by their ``repr()``, and having that ``repr()`` be easy to parse, is useful and can save time and effort in understanding and debugging code. However, the enums with mixed-in data types (``IntEnum``, ``IntFlag``, and the new ``StrEnum``) need to be more backwards compatible with the constants they are replacing -- specifically, ``str(replacement_enum_member) == str(original_constant)`` should be true (and the same for ``format()``). IntEnum, IntFlag, and StrEnum should be as close to a drop-in replacement of existing integer and string constants as is possible. Towards that goal, the str() output of each should be its inherent value; e.g. if ``Color`` is an ``IntEnum``:: >>> Color.RED >>> str(Color.RED) '1' >>> format(Color.RED) '1' Note that format() already produces the correct output in 3.10, only str() needs updating. As much as possible, the ``str()`, ``repr()``, and ``format()`` of enum members should be standardized across the stardard library. The repr() of Flag currently includes aliases, which it should not; fixing that will, of course, already change its ``repr()`` in certain cases. Specification = There a three broad categories of enum usage: - standard: Enum or Flag a new enum class is created, and the members are used as ``class.member_name`` - drop-in replacement: IntEnum, IntFlag, StrEnum a new enum class is created which also subclasses ``int`` or ``str`` and uses ``int.__str__`` or ``str.__str__``; the ``repr`` can be changed by using the ``global_enum`` decorator - user-mixed enums and flags the user creates their own integer-, float-, str-, whatever-enums instead of using enum.IntEnum, etc. Some sample enums:: # module: tools.py class Hue(Enum): # or IntEnum LIGHT = -1 NORMAL = 0 DARK = +1 class Color(Flag): # or IntFlag RED = 1 GREEN = 2 BLUE = 4 class Grey(int, Enum): # or (int, Flag) BLACK = 0 WHITE = 1 Using the above enumerations, the following table shows the old and new behavior, while the last shows the final result: +-+--+-++---+---++---+ | type | enum repr() | enum str() | enum format() | flag repr() | flag str() | flag format() | +-+--+-++---+---++---+ | standard| 3.10 | || | | Color.RED|GREEN| Color.RED|GREEN | | +--+-++---+---++---+ | | new | || | | Color.RED|Color.GREEN | Color.RED|Color.GREEN | +-+--+-++---+---++---+ +-+--+-++---+---++---+ | user mixed | 3.10 | || 1 || | 1 | | +--+-++---+---++---+ | | new | || G
[Python-ideas] Re: builtins for running context managers
On 7/13/21 2:20 PM, Thomas Grainger wrote: > On Tue, 13 Jul 2021, 21:31 Ethan Furman, wrote: >> On 7/13/21 12:43 PM, Thomas Grainger wrote: >>> I used the order I did because it's idiomatic to return the value the user needs >>> followed by the value the user wants. >> >> citation? > > Like the nodeback interface, it's (err, val) Isn't that javascript? Javascript idioms are not (necessarily) Python idioms. -- ~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/LRDMINVNXXTAWBWMPZWYDMTCPVR5ZHG6/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: builtins for running context managers
On 7/13/21 12:43 PM, Thomas Grainger wrote: > I used the order I did because it's idiomatic to return the value the user needs > followed by the value the user wants. citation? -- ~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/SBUNQOCAQTBWIGRUIP5BMMEEYEN7Y4F4/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: disallow assignment to unknown ssl.SSLContext attributes
On 6/26/21 1:55 PM, Marc-Andre Lemburg wrote: > On 26.06.2021 21:32, Ethan Furman wrote: >> In most cases I would agree with you, but in this case the object is security >> sensitive, and security should be much more rigorous in ensuring correctness. > > Isn't this more an issue of API design rather than Python's > flexibility when it comes to defining attributes ? I think it's both, with the majority of the responsibility being on the API design. > IMO, a security relevant API should not use direct attribute > access for adjusting important parameters. Those should always > be done using functions or method calls which apply extra sanity > checks and highlight issues in form of exceptions. Agreed -- but Python's nature makes it easy to use attribute access to make adjustments, and that should also be constrained in security conscious objects. -- ~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/W37274R4WDTRXG2Y2U4RPTFHWXBEGZFE/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: disallow assignment to unknown ssl.SSLContext attributes
[oops, hit Send too soon] On 6/25/21 5:20 PM, Eric V. Smith wrote: > It seems like many of the suggestions are SSLContext specific. I don't think we should be adding > __slots__ or otherwise redefining the interface to that object. Isn't this a general "problem" in > python... In most cases I would agree with you, but in this case the object is security sensitive, and security should be much more rigorous in ensuring correctness. -- ~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/WQV7NWCTBIFSJTD3XXSEU5PB2KEFHU7O/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: disallow assignment to unknown ssl.SSLContext attributes
On 6/25/21 5:20 PM, Eric V. Smith wrote: > It seems like many of the suggestions are SSLContext specific. I don't think we should be adding > __slots__ or otherwise redefining the interface to that object. Isn't this a general "problem" in > python... ___ 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/5FL7K6W3V6URWNE3PWHJVC3STOVRHJLD/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] name for new Enum decorator
Greetings! The Flag type in the enum module has had some improvements, but I find it necessary to move one of those improvements into a decorator instead, and I'm having a hard time thinking up a name. What is the behavior? Well, a name in a flag type can be either canonical (it represents one thing), or aliased (it represents two or more things). To use Color as an example: class Color(Flag): RED = 1# 0001 GREEN = 2 # 0010 BLUE = 4 # 0100 PURPLE = RED | BLUE# 0101 WHITE = RED | GREEN | BLUE # 0111 The flags RED, GREEN, and BLUE are all canonical, while PURPLE and WHITE are aliases for certain flag combinations. But what if we have something like: class Color(Flag): RED = 1# 0001 BLUE = 4 # 0100 WHITE = 7 # 0111 As you see, WHITE is an "alias" for a value that does not exist in the Flag (0010, or 2). That seems like it's probably an error. But what about this? class FlagWithMasks(IntFlag): DEFAULT = 0x0 FIRST_MASK = 0xF FIRST_ROUND = 0x0 FIRST_CEIL = 0x1 FIRST_TRUNC = 0x2 SECOND_MASK = 0xF0 SECOND_RECALC = 0x00 SECOND_NO_RECALC = 0x10 THIRD_MASK = 0xF00 THIRD_DISCARD = 0x000 THIRD_KEEP = 0x100 Here we have three flags (FIRST_MASK, SECOND_MASK, THIRD_MASK) that are aliasing values that don't exist, but it seems intentional and not an error. So, like the enum.unique decorator that can be used when duplicate names should be an error, I'm adding a new decorator to verify that a Flag has no missing aliased values that can be used when the programmer thinks it's appropriate... but I have no idea what to call it. Any nominations? -- ~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/C4JRARG6RZKRJCD7745JIK6ZMFRYM76M/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Introduce constants in Python (constant name binding)
On 5/25/21 8:33 AM, Damian Shaw wrote: > On Tue, May 25, 2021 at 11:02 AM Ethan Furman wrote: >> On 5/25/21 5:23 AM, Chris Angelico wrote: >>> On Tue, May 25, 2021 at 9:55 PM Shreyan Avigyan wrote: >>>> The proposed syntax is as follows, >>>> >>>> constant x = 10 >>>> constant y = ["List"] >>>> constant z: str = "Hi" >>> >>> https://docs.python.org/3/library/typing.html#typing.Final >>> >>> Already exists :) >> >> Optional typing != core Python. > > It's still a Python feature even if it's not a language feature, it's well defined > by PEP and any type checker wanting to implement type hinting to spec must include it. > > Further type hinting allows developers who want to use a Constant / Final feature get > the benefit already from type hinting, whereas developers who want to stick to the > pythonic philosophy of "we're all consenting adults here" can still mess with the > code but know it's not supported at all. As far as I can see it's the best of both > worlds. > > Could you please list in your proposal the real world benefits vs. the existing type > hinting feature? To be clear, this is not my proposal, and I completely agree with David Mertz. I am -1 on the proposal. Nevertheless, the proposal is not satisfied by a stdlib module that is completely ignored by the Python runtime -- that was the only point I was trying to make. -- ~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/UHMC44E7OVH3OT4ZQ2ZXV6MD64GCT2ZN/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Introduce constants in Python (constant name binding)
On 5/25/21 5:23 AM, Chris Angelico wrote: > On Tue, May 25, 2021 at 9:55 PM Shreyan Avigyan wrote: >> The proposed syntax is as follows, >> >> constant x = 10 >> constant y = ["List"] >> constant z: str = "Hi" > > https://docs.python.org/3/library/typing.html#typing.Final > > Already exists :) Optional typing != core Python. -- ~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/NZUWNBFWI5ESOW6CVMQA7CZTRNFVJJLA/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Decorators on variables
On 5/24/21 6:36 PM, micro codery wrote: > Variable decorators have been suggested here before, as have new statements > that could also achieve the same level of access to the binding name. However > I propose a much more restricted syntax that would make for less edge cases > where what is actually passed to the decorator callable may be ambiguous. > #instead of GREEN = "GREEN" > @str GREEN > #instead of Point = namedtuple("Point", "x y z") > @namedtuple("x y z") Point > #instead of Point = make_dataclass("Point", [("x", int), ("y", int), ("z", int)]) > @make_dataclass([("x", int), ("y", int), ("z", int)]) Point > #instead of Colors = Enum("Colors", "RED GREEN BLUE") > @Enum("RED GREEN BLUE") Colors > class Colors(Enum): > @str RED > @str GREEN > @str BLUE > #instead of UUIDType = NewType("UUIDType", str) > @NewType UUIDType: str I think that looks very interesting. -- ~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/CFFC2TCFTGCR3BY6U5JY5KHB6QB46U6P/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: division of integers should result in fractions not floats
On 5/14/21 2:34 PM, Eric V. Smith wrote: > My understanding of the proposal is that OP is only talking about / becomes a > Fraction. So: > > x=1 > x/2 # unchanged, still yields a float. > > It's only literals like "1/2" that would become Fraction(1,2). Ah -- which means we end up with fractions and fraction math which results in memory and time issues, since most fraction/fraction operations return, unsurprisingly, fractions. -- ~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/LO2S4OYQA3PMDBYSPAOLZI4Y36FFGGSH/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: division of integers should result in fractions not floats
On 5/14/21 5:12 AM, Martin Teichmann wrote: > In order to showcase how that would look like, let me give an example session: > > >>> 5/6-4/15 > 17/30 > >>> a=22/7 > >>> f"{a}" > '22/7' > >>> f"{a:f}" > '3.142857' > >>> from decimal import Decimal > >>> Decimal(1/3) > Decimal('0.') This looks very interesting! I see some confusion on all sides on what, exactly, you are proposing. As best as I can figure, the rules for your conversions are something like (where .div. is division and .op. is any other operation): 1) int .div. int --> fraction 2) int .op. fraction --> fraction 3) fraction .op. non-fraction --> float What I am not sure of: 4) fraction .op. fraction --> ??? 5) fraction .op. non-fraction --> ??? Am I correct on 1-3? What are you proposing as regards 4 and 5? -- ~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/GIHYCE2R32FXCNAWYJR3S3ICAH7KMCED/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: division of integers should result in fractions not floats
On 5/14/21 1:07 PM, Paul Moore wrote: > All I'm trying to say is "I think that having 1/2 > mean something different than 1 / 2 is unacceptable, because it's too > easy for people to misunderstand". Agreed. Significant white space for control flow is great; for specifying data types it's horrible. -- ~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/3M7Z6ES7Y4MOFIHDESUGRWELCENYXAD5/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Add support for private variables, methods and functions in Python
On 5/6/21 10:44 PM, Shreyan Avigyan wrote: > Anyway this thread is closed. As you may have noticed, this is a mailing list -- no thread is closed. I've seen posts to three-year-old threads. -- ~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/QYGH5YCWRSM4PBJDPUVDPDE52YPGGL6T/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] list etiquette [was: Add support for private variables, methods and functions in Python]
On 5/6/21 6:26 AM, Shreyan Avigyan wrote: > Chris wrote: >> Please actually quote some text so we know who you're responding to, >> what you're talking about, etc. > > I'm actually telling to read my comment here https://mail.python.org/archives/list/python-ideas@python.org/message/426EPANCVEGZV2AZL7MWNG67BTZMORNG. See the Conclusion section in there. I, and many others, read Python List with a mail reader, not a web reader, and have zero desire to start clicking on links to see what you said somewhere else. Copy and paste is your friend. Further, by not quoting others, we have no idea what interpretation of your post you are disagreeing with. So: - quote the portions of posts you are replying to - rewrite, or copy & paste, the portions of your own posts that are relevant - explain why the other respondent's interpretation is not correct - don't bring up security if that's not a primary motivating factor - if your proposal changes, change the subject line to match (or start a new thread) -- ~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/M3TPT6IU3CFYMKJF3KVNRCBN3ESKKEEX/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Python Idea - extension of 'with'
On 4/9/21 11:33 AM, anthony.flury via Python-ideas wrote: On 09/04/2021 19:02, Guido van Rossum wrote: But if there are two proposals with conflicting semantics for the same syntax that kills both ideas, doesn’t it? Because apparently it’s not clear what the syntax should mean. Surely it depends (if we adopt a proposal) how we document it. You could argue that very few syntax elements are entirely clear unless we explain it - which is what the point of the documentation. For example for someone who doesn't know what 'with' does, it isn't necessarily clear (just from the syntax) that 'with' ensures finalizing of resources when an exception occurs - the documentation has to explain that. Especially if one is coming from, say, Foxpro, where `with` is a shortcut for omitting the class name for attribute lookups. -- ~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/BROGBEJET7ZOFQXTSPHY2HGEHGWIHSUA/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Python Idea - extension of 'with'
On 4/8/21 2:40 PM, Chris Angelico wrote: At least in this form, it's clear that there's a sharp distinction between the stuff around the outside of the 'with' block and the stuff inside it. The semantics, as suggested, give 'with' blocks two distinct exception-management scopes, which mostly but do not entirely overlap. It's not a problem to rigorously define the semantics, but as evidenced here, people's intuitions will vary depending on which context manager is being used. It's absolutely obvious that the OP's example should let you catch errors from open(), and equally obvious that suppressing BaseException should mean that nothing gets caught. That's the problem here. As such, I'm -0.5 on this. It's a kinda nice feature, but all it really offers is one less indentation level, and the semantics are too confusing. I, on the other hand, would love for something along those lines -- I find it massively annoying to have to wrap a with-block, which is supposed to deal with exceptions, inside a try/except block, because the exceptions that `with` deals with are too narrowly focused. Of course, I also prefer def positive(val): "silly example" if val > 0: return True else: return False over def positive(val): "silly example" if val > 0: return True return False because the first more clearly says "either this happens, or that happens". Likewise, having the excepts line up with the `with` visually ties the code together. Granted, this mostly boils down to personal preference. -- ~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/3JIGEJAEAJIQXITUCMSKH2ZOK6WSUGJS/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Python Idea - extension of 'with'
On 4/8/21 1:21 PM, Chris Angelico wrote: On Fri, Apr 9, 2021 at 6:16 AM Ethan Furman wrote: On 4/8/21 11:25 AM, Chris Angelico wrote: Similar question: What would be the semantics of this? with contextlib.suppress(BaseException): a = b / c except BaseException as e: print(e) What types of exception could be caught and what types couldn't? Well, if every exception is derived from BaseException (they are) and contextlib.suppress(BaseException) suppresses all BaseException-derived exceptions (it does) then the semantics of the above are: - "a" will be the result of "b / c" if no exception occurs - otherwise, "a" will be whatever it was before the with-block - no exception will ever be caught by the except-clause Generally speaking, no exception that a context manager handles (i.e. suppresses) will ever be available to be caught. What about NameError looking up contextlib, or AttributeError looking up suppress? Will they be caught by that except clause, or not? Ah, good point -- those two would get caught, as they happen before contextlib.suppress() gets control. Thank you for making my point: your assumption is completely the opposite of the OP's, given the same syntactic structure. The guidance should be: `try with` behaves exactly as `try/except with a with`, meaning that NameError and AttributeError for those two reasons would still be caught. Yes, it's easy to miss that at first glance, but it's just as easy to miss in the traditional try/except layout: ```python try: with contextlib.suppress(BaseException): # do stuff except BaseException as e: print(e) ``` How many people are going to look at that and think, "oh, NameError and AttributeError can still be caught" ? -- ~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/KANA7OVE4VLYZWWDCRTCO6F6GQDZ3XZ2/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Python Idea - extension of 'with'
On 4/8/21 11:25 AM, Chris Angelico wrote: Similar question: What would be the semantics of this? with contextlib.suppress(BaseException): a = b / c except BaseException as e: print(e) What types of exception could be caught and what types couldn't? Well, if every exception is derived from BaseException (they are) and contextlib.suppress(BaseException) suppresses all BaseException-derived exceptions (it does) then the semantics of the above are: - "a" will be the result of "b / c" if no exception occurs - otherwise, "a" will be whatever it was before the with-block - no exception will ever be caught by the except-clause Generally speaking, no exception that a context manager handles (i.e. suppresses) will ever be available to be caught. -- ~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/6MECZSWSSBIJUTZQWLKSCJKO7PRZA5WT/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: dataclasses keyword-only fields, take 2
On 3/16/21 1:19 PM, Brendan Barnwell wrote: On 2021-03-16 06:20, Eric V. Smith wrote: I'd like to avoid field() as much as possible. I think it's just too easy to miss what it's doing, since it has many arguments. And I'd like to make it easy to have a style that encourages all non-keyword-only fields to come first. From my perspective it's quite the contrary. `field` is an actual function call and its arguments may affect its behavior in the way that arguments generally affect function calls. This thing with a dummy attribute holding a magic value whose sequential position in the class body influences *different* attributes based on their *relative* sequential position. . . I find that much more confusing and strange. I think Simão's version where you give a class-level default for keyword-only-ness and then override it with field() arguments where necessary is much cleaner. I agree with Eric. The class body is basically a vertical representation of the horizontal `__init__` header. As such, `KW_ONLY` and (maybe in the future) POS_ONLY match very nicely. -- ~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/S6EMN2BDFZMESALHLAPLZDUGN2BJL7LF/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Enum: determining if a value is valid
On 3/16/21 11:43 AM, Matt Wozniski wrote: On Tue, Mar 16, 2021, 2:39 PM Marco Sulla wrote: On Tue, 16 Mar 2021 at 05:38, Matt Wozniski wrote: Color.from_value(1) # returns Color.RED What if I have an alias? Aliases are different names for a single Enum member, so a by-value search is unaffected by them. That's a problem with any attempt to find an enum member by value, since values aren't guaranteed to be unique. With either proposal, we'd just need to pick one - probably the one that appears first in the class dict. This is incorrect. Enum values are unique -- there is only one member that will be returned for any given value. Aliases are additional names for that one member: from enum import Enum class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 REDD = 1# to support a silly misspelling >>> Color.RED >>> Color(1) >>> Color['RED'] >>> Color['REDD'] Notice that 'REDD' returns the RED member. There is no member named REDD in Color. -- ~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/XBGO35VFGC7CQLIZJTKH6EAXEKCJJQRC/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Enum: determining if a value is valid
On 3/15/21 11:27 AM, Guido van Rossum wrote: On Mon, Mar 15, 2021 at 10:53 AM Ethan Furman wrote: Part of the reason is that there are really two ways to identify an enum -- by name, and by value -- which should `__contains__` work with? The two sets don't overlap, so we could allow both. (Funny interpretations of `__contains__` are not unusual, e.g. substring checks are spelled 'abc' in 'fooabcbar'.) They could overlap if the Enum is a `str`-subclass -- although having the name of one member match the value of a different member seems odd. I think I like your constructor change idea, with a small twist: Color(value=, name=, default=) This would make it possible to search for an enum by value or by name, and also specify a default return value (raising an exception if the default is not set and a member cannot be found). So specifically this would allow (hope my shorthand is clear): ``` Color['RED'] --> Color.RED or raises Color(1) -> Color.RED or raises Color(1, default=None) -> Color.RED or None Color(name='RED', default=None) -> Color.RED or None ``` This seems superficially reasonable. I'm not sure what Color(value=1, name='RED') would do -- insist that both value and name match? Would that have a use case? I would enforce that both match, or raise. Also not sure what the use-case would be. My remaining concern is that it's fairly verbose -- assuming we don't really need the name argument, it would be attractive if we could write Color(1, None) instead of Color(1, default=None). Note that instead of Color(name='RED') we can already write this: ``` getattr(Color, 'RED') -> Color.RED or raises getattr(Color, 'RED', None) -> Color.RED or None Very good points. Everything considered, I think I like allowing `__contains__` to verify both names and values, adding `default=` to the constructor for the value-based "gimme an Enum or None" case, and recommending `getattr` for the name-based "gimme an Enum or None" case. -- ~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/UQBSDZQJWBKMOVSUES7HEDJTYR76Y5N2/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Enum: determining if a value is valid
On 3/12/21 5:28 PM, Guido van Rossum wrote: On Fri, Mar 12, 2021 at 1:52 PM Ethan Furman wrote: A question that comes up quite a bit on Stackoverflow is how to test to see if a value will result in an Enum member, preferably without having to go through the whole try/except machinery. A couple versions ago one could use a containment check: if 1 in Color: but than was removed as Enums are considered containers of members, not containers of the member values. Maybe you were a bit too quick in deleting it. Was there a serious bug that led to the removal? Could it be restored? Part of the reason is that there are really two ways to identify an enum -- by name, and by value -- which should `__contains__` work with? At this point I see three options: 1) add a `get(value, default=None)` to EnumMeta (similar to `dict.get()` But the way to convert a raw value to an enum value is Color(1), not Color[1], so Color.get(1) seems inconsistent. Very good point. Maybe you can just change the constructor so you can spell this as Color(1, default=None) (and then check whether that's None)? An interesting idea. 2) add a recipe to the docs But what would the recipe say? Apparently you're looking for a one-liner, since you reject the try/except solution. The recipe would be for a method that could be added to an Enum, such as: @classmethod def get_by_value(cls, value, default=None): for member in cls: if member.value == value: return member return default 3) do nothing Always a good option. :-) Yes, but not always a satisfying one. :) Where's that StackOverflow item? How many upvotes does it have? 93 - How do I test if int value exists in Python Enum without using try/catch? https://stackoverflow.com/q/43634618/208880 25 - How to test if an Enum member with a certain name exists? https://stackoverflow.com/q/29795488/208880 3 - Validate value is in Python Enum values https://stackoverflow.com/q/54126570/208880 2 - How to check if string exists in Enum of strings? https://stackoverflow.com/q/63335753/208880 I think I like your constructor change idea, with a small twist: Color(value=, name=, default=) This would make it possible to search for an enum by value or by name, and also specify a default return value (raising an exception if the default is not set and a member cannot be found). -- ~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/LJXMAORK2JVYTPQQ332NFEV2JPVFVJAX/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Add an export keyword to better manage __all__
On 3/14/21 12:42 PM, Stestagg wrote: The value of being able to (in specific cases) reach into third-party code, and customize it to work for your specific situation should not be disregarded. I completely agree with this. One of the hallmarks of Python is the ability to query, introspect, and modify Python code. It helps with debugging, with experimenting, with fixing. Indeed, one of the few frustrating bits about Python is the inability to work with the C portions as easily as the Python portions (note: I am /not/ suggesting we do away with the C portions). What would be the benefits of locking down modules in this way? -- ~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/KIFAVTRMIPCVAX2RZ7NDSTDM46AHSDWK/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Enum: determining if a value is valid
On 3/12/21 2:49 PM, Ricky Teachey wrote: On Fri, Mar 12, 2021 at 4:52 PM Ethan Furman wrote: A question that comes up quite a bit on Stackoverflow is how to test to see if a value will result in an Enum member, preferably without having to go through the whole try/except machinery. Could this be an instance where match-case might become the canonical solution? I'm probably getting the syntax wrong, but maybe it would be something like: match value: case MyEnum(): assert isinstance(value, MyEnum) case _: assert not isinstance(value, MyEnum) The use case is when you have an unknown value that may or may not convert into an Enum member. So a three-member Enum would look something like: ```python match value: case MyEnum(): pass case 1|2|3: value = MyEnum(value) case _: handle_error_or_use_default() ``` Seven lines of code. try/except would be something like: ```python try: value = MyEnum(value) except ValueError: handle_error_or_use_default() ``` vs what I'm envisioning: ```python value = MyEnum.get(value, some_default) ``` or maybe ```python value = MyEnum.get(value) if value is None: handle_error() ``` -- ~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/Z7C36KHOFDDM6REA4PN6GPPYOJ22DPBY/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Enum: determining if a value is valid
A question that comes up quite a bit on Stackoverflow is how to test to see if a value will result in an Enum member, preferably without having to go through the whole try/except machinery. A couple versions ago one could use a containment check: if 1 in Color: but than was removed as Enums are considered containers of members, not containers of the member values. It was also possible to define one's own `_missing_` method and have it return None or the value passed in, but that has also been locked down to either return a member or raise an exception. At this point I see three options: 1) add a `get(value, default=None)` to EnumMeta (similar to `dict.get()` 2) add a recipe to the docs 3) do nothing Thoughts? -- ~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/N6C2ROUCSLEPPH34BTFQNQE4ZM63WUWC/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Allow trailing operators [was: allow initial comma]
On 3/12/21 9:04 AM, Henk-Jaap Wagenaar wrote: ( Q(user=user) | Q(is_deleted=True) | ) I am happy to flesh this out more, but as this discussion was ongoing, I thought I would throw it out here and see what people think? Are there potential problems with this e.g. with parsing it? Yes, there are major issues for the human parser: it looks like an error. I suspect it would also contribute to errors. -- ~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/4CB5KJFWPE7N7XEYLO7FKDOECLUHHWMY/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Implicit line continuation for method chaining
On 3/12/21 7:50 AM, Paul Bryan wrote: My inclination would be to cede code formatting to a tool like Black and focus on function: https://black.readthedocs.io/en/stable/ We still have to read it after Black munges it. Like Paul said, add parentheses -- it works for method chaining, string concatenation, etc. -- ~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/M2IAKNCMJZZTF6WP674M2SD3U5VIMWP6/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Dataclasses, keyword args, and inheritance
On 3/11/21 10:50 AM, Paul Bryan wrote: On Thu, 2021-03-11 at 10:45 -0800, Ethan Furman wrote: On 3/10/21 9:47 PM, Eric V. Smith wrote: I'm not sure of the best way to achieve this. Using flags to field() doesn't sound awesome, but could be made to work. Or maybe special field names or types? I'm not crazy about that, but using special types would let you do something like: @dataclasses.dataclass class Point: x: int = 0 _: dataclasses.KEYWORD_ONLY y: int z: int t: int = 0 Maybe something like this? class Hmm: # this: int that: float # pos: '/' # these: str those: str # key: '*' # some: list >>> Hmm.__dict__['__annotations__'] { 'this': , 'that': , 'pos': '/', 'these': , 'those': , 'key': '*', 'some': , } The name of 'pos' and 'key' can be convention, since the actual name is irrelevant. They do have to be unique, though. ;-) It's current convention (and is used by typing module and static type checkers) that string annotations evaluate to valid Python types. So make '/' and '*' be imports from dataclasses: from dataclasses import dataclass, PosOnly, KWOnly -- ~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/6L4W5OB23FBWZ7EZYDNCYSGT2CUAKYSX/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Dataclasses, keyword args, and inheritance
On 3/10/21 9:47 PM, Eric V. Smith wrote: I'm not sure of the best way to achieve this. Using flags to field() doesn't sound awesome, but could be made to work. Or maybe special field names or types? I'm not crazy about that, but using special types would let you do something like: @dataclasses.dataclass class Point: x: int = 0 _: dataclasses.KEYWORD_ONLY y: int z: int t: int = 0 Maybe something like this? class Hmm: # this: int that: float # pos: '/' # these: str those: str # key: '*' # some: list >>> Hmm.__dict__['__annotations__'] { 'this': , 'that': , 'pos': '/', 'these': , 'those': , 'key': '*', 'some': , } The name of 'pos' and 'key' can be convention, since the actual name is irrelevant. They do have to be unique, though. ;-) -- ~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/BIAVX4O6JRPQY7S3XG2IX6BSBZLAR2NS/ Code of Conduct: http://python.org/psf/codeofconduct/
[Python-ideas] Re: Dataclasses, keyword args, and inheritance
On 3/11/21 4:20 AM, Ricky Teachey wrote: This might be a bit of an extreme step to take, but has new syntax for this ever been discussed? Here I am using the same indicator for keyword arguments as in a function signature, hanging on a line by itself: @dataclasses.dataclass class Comparator: a: Any b: Any * key: Optional[Callable[whatever]] = None Could also support the positional only version: @dataclasses.dataclass class Comparator: / # args become positional after this line a: Any b: Any * # args become kwd args after this line key: Optional[Callable[whatever]] = None Actually, the '/' indicates that names /before/ it are positional only. -- ~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/W4U5PCRBEWQZCZOA3LV46W27TGQD6EC6/ Code of Conduct: http://python.org/psf/codeofconduct/