[Python-ideas] Re: C#-style "as" casting syntactic sugar for type hints

2023-03-23 Thread Damian Shaw
But doesn't date.strftime returns str not Any:
https://github.com/python/typeshed/blob/main/stdlib/datetime.pyi#L75 ?

Damian

On Thu, Mar 23, 2023 at 10:00 PM Will Bradley 
wrote:

> This is some real code I wrote the other day:
> payload = {
> "birthDate": str(date.strftime('%m/%d/%Y')),
> ...
> }
> Due to the fact that date.strftime returns Any type, for my type hinting
> and autocomplete to work I either need to pass it to the str function or
> typing.cast(str, date). It would be nice if I could just write "birthDate":
> date.strftime(r'%m/%d/%Y') as str, like in C#. It's shorter, (in my
> opinion) more readable, and avoids having to unnecessarily call
> a constructor or import typing.cast.
>
> It's important to note that this would be syntactic sugar for typing.cast—
> it wouldn't call any constructor or affect program state, just increase the
> power of the type hinting system.
>
> Will Bradley
> ___
> 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/ZP6UHIHBOIZLO63QJPYTUSFXQBEKJVV4/
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/D4KWKVWF3HQQHHCAKF3OFNOQN7OLO4G7/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: A modulo operator consistent with euclidean division.

2022-03-18 Thread Damian Shaw
Can you give some examples of how it would be used differently than the
current modulo operator and what value it would bring?

For those who have not taken number theory courses in a long time (or
never!) it's not clear how this would be useful for Python.

Damian (he/him)

On Fri, Mar 18, 2022 at 11:10 AM Nathan Levett 
wrote:

> Howdy python gang,
>
> First time posting here ~ I've recently encountered that python does not
> have an OOTB operator for modulo that is consistent with Euclidean
> division. Although it should be easy for anyone who wants this to create it
> themselves, it struck me as odd that it was not an already included
> feature. I was even more shocked to see a list indicating that most
> languages don't include one consister with Euclidean division
> (disheartening to realise that the number theory way of doing things is not
> the default). I was so shocked at it's lack from python that it motivated
> me to post this, I suppose!
>
> I guess I'm posting to check how open anyone would be to the idea? I'm not
> sure if '%%' is defined anywhere, but it seemed like an intuitive
> suggestion if not already used as an operator, parallel to the syntax of
> the '**' operator.
>
> Keen to know how open y'all're to it!
> ___
> Python-ideas mailing list -- python-ideas@python.org
> To unsubscribe send an email to python-ideas-le...@python.org
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at
> https://mail.python.org/archives/list/python-ideas@python.org/message/KRISFMIOXQOXFH5Y4XYUMBEONMCCOOQH/
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/R3MMQ3DTHVCQCSS5RTAMRDZ6LA5KR7IA/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Make 10**400 / 1e200 work?

2022-02-19 Thread Damian Shaw
That sounds like a lot of extra checks to put on "/" when the error message
is clear and the user could implement their own checks if they are running
into this niche use case and do 10**400 / int(1e200).

Damian (he/him)

On Sat, Feb 19, 2022 at 8:36 AM Stefan Pochmann 
wrote:

> It crashes because it tries to convert 10**400 to a float and that fails:
>
> >>> 10**400 / 1e200
> Traceback (most recent call last):
>   File "", line 1, in 
> 10**400 / 1e200
> OverflowError: int too large to convert to float
>
> But with two ints it succeeds:
>
> >>> 10**400 / 10**200
> 1e+200
>
> Note that 1e200 is an integer:
>
> >>> 1e200.is_integer()
> True
>
> So that could losslessly be converted to int, and then the division would
> succeed:
>
> >>> 10**400 / int(1e200)
> 1e+200
>
> So could/should 10**400 / 1e200 be implemented to do that instead of
> raising the error? Or is it a too rare use case and not worth the effort,
> or does something else speak against it?
> ___
> Python-ideas mailing list -- python-ideas@python.org
> To unsubscribe send an email to python-ideas-le...@python.org
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at
> https://mail.python.org/archives/list/python-ideas@python.org/message/O7FE5AAWPA77QRQPKJVT6AB3XK7QPUZG/
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/LBNH5IOG2LI6TU5IVCFI76GPPOLV4ZZF/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Missing expandvars equivalent in pathlib

2022-02-10 Thread Damian Shaw
FYI there was a patch for this in the past and it was rejected:
https://bugs.python.org/issue21301

Damian (he/him)

On Thu, Feb 10, 2022 at 12:04 PM Christopher Barker 
wrote:

> +1 -- I would really like pathlib to be able to used for everything one
> would need to do with paths.
>
> -CHB
>
>
> On Thu, Feb 10, 2022 at 3:05 AM anthony.flury via Python-ideas <
> python-ideas@python.org> wrote:
>
>> All,
>>
>> I know that *os.path* includes a function *expandvars(..)* which expands
>> any environment variables in a given path, but from looking at the
>> *pathlib* documentation It seems there is
>> no equivalent to *os.path.expandvars(..) on any class* in *pathlib*, and
>> the recommendation seems to be to use *pathlib* to do any and all path
>> manipulations, with the exception of expanding environment variables.
>>
>> It appears that the recommended *pathlib* compatible code to fully
>> convert any file path (which may have environment variables and or ~ or
>> ~user constructs) to a fully resolved absolute path is :
>>
>> import os.path
>>
>> import pathlib
>>
>> given_path = input('Provide the full path')
>>
>> abs_path =
>> pathlib.Path(os.path.expandvars(pathlib.Path(givenpath).expanduser())).resolve()
>>
>> It seems to me that *pathlib.Path* would benefit massively from an
>> *os.path.expandvars(..)* equivalent - so that the equivalent code could
>> be :
>>
>> import os.path
>>
>> import pathlib
>>
>> given_path = input('Provide the full path')
>>
>> abs_path = pathlib.Path(givenpath).expandvars().expanduser().resolve()
>>
>> I know the need to do this is likely to be a corner case, but even still
>> it continues dependency on *os.path* for those programs that need to
>> resolve environment variables in paths, and increases the cognitive load
>> for this operation, , and it seems like a missed feature in *pathlib*
>>
>> A change such as this shouldn't affect backwards compatibility.
>>
>> What do people think - have I missed something or is pathlib missing
>> something ?
>>
>>
>>
>> *Pathlib documentation *
>>
>> *https://docs.python.org/3/library/pathlib.html#module-pathlib
>> *
>>
>>
>> --
>> Anthony Flury
>> *Moble*: +44 07743 282707
>> *Home*: +44 (0)1206 391294
>> *email*: anthony.fl...@btinternet.com
>> ___
>> 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/IJSOTVIDYLWRYEXFZCOFWSCIYHORQS6Z/
>> Code of Conduct: http://python.org/psf/codeofconduct/
>>
>
>
> --
> Christopher Barker, PhD (Chris)
>
> Python Language Consulting
>   - Teaching
>   - Scientific Software Development
>   - Desktop GUI and Web Development
>   - wxPython, numpy, scipy, Cython
> ___
> Python-ideas mailing list -- python-ideas@python.org
> To unsubscribe send an email to python-ideas-le...@python.org
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at
> https://mail.python.org/archives/list/python-ideas@python.org/message/X4CAQWE2QQKV2HKAO3PQAWUZ23Z4MMBW/
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/3DML6XHOOGB3MIGBTI2LN62EOMYW5Y3D/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Adding sortedconatiners to Python or merge the ideas?

2022-02-03 Thread Damian Shaw
This was very recently discussed at length:
https://mail.python.org/archives/list/python-...@python.org/thread/YB2JD477TKPB2HTXDW6ZXUBD6NFFFHHJ/#YB2JD477TKPB2HTXDW6ZXUBD6NFFFHHJ

Damian (he/him)

On Thu, Feb 3, 2022 at 11:51 AM Abdur-Rahmaan Janhangeer <
arj.pyt...@gmail.com> wrote:

> Greetings,
>
> This library* seems to be used by many people for some treemap operations.
> Would it be a good idea to include it in upcoming versions? Leetcode
> has it by default for the lack of a similar something in Python. I did not
> check,
> but it seems other languages cater to structures better.
>
> * http://www.grantjenks.com/docs/sortedcontainers/
>
> Thanks.
>
> Kind Regards,
>
> Abdur-Rahmaan Janhangeer
> about  | blog
> 
> github 
> Mauritius
> ___
> 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/ASMXPU6O2NDZG32MQFMYQKCKTFKET4FE/
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/VM2QRXQ54FZPSA5UZ7PKNYRDUKBEDLDM/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Shorthand syntax for lambda functions that have a single parameter

2021-09-29 Thread Damian Shaw
I find this approach too cryptic compared to reading regular Python
notation, my brain has to mode switch to make sense of it. Would a little
extra ?: be too much add to make clear it's a lambda function, e.g.
?: ? > 0 instead of ? > 0

Also either approach *could *add multi-argument lambdas:
?1, ?2: ?1 > ?2 or just ?1 > ?2

I wonder though if there's a nice approach to have a no argument lambda? 樂

Damian (he/him)



On Wed, Sep 29, 2021 at 8:55 AM Dominik Vilsmeier 
wrote:

> Lambda functions that have a single parameter are a common thing, e.g. for
> "key" functions: `sorted(items, key=lambda x: x['key'])`. For these cases
> however, the rather long word "lambda" together with the repetition of the
> parameter name, results in more overhead than actual content (the
> `x['key']`) and thus makes it more difficult to read. This is also a
> difficulty for `map` and `filter` for example where there's lots of visual
> overhead when using a lambda function and hence it's difficult to read:
> `filter(lambda x: x > 0, items)` or `map(lambda x: f'{x:.3f}', items)`.
>
> Hence the proposal is to add a new syntax via the new token `?`. For the
> examples above:
>
> * `sorted(items, key=?['key'])`
> * `filter(? > 0, items)`
> * `map(f'{?:.3f}', items)`
>
> The rules are simple: whenever the token `?` is encountered as part of an
> expression (at a position where a name/identifier would be legal), the
> expression is replaced by a lambda function with a single parameter which
> has that expression as a return value, where any instances of `?` are
> replaced by the name of that single parameter. For example:
>
> * `?['key']` translates to `lambda x: x['key']`
> * `? > 0` translates to `lambda x: x > 0`
> * `f'{?:.3f}'` translates to `lambda x: f'{x:.3f}'`
> * `?*?` translates to `lambda x: x*x`
>
> With the difference that the replacement function would use an unnamed
> parameter, i.e. not shadowing any names from outer scopes. So `? * x` would
> use `x` from enclosing scopes, not as the lambda parameter.
>
> Regarding operator precedence, the rules would be similar as for lambda
> functions, i.e. it will include as much in the expression as it would for a
> lambda function.
>
> To find more example use cases, I used `grep -rnE 'lambda
> [_a-zA-Z][_a-zA-Z0-9]*:' Lib/` on the CPython standard library to find
> single parameter lambda functions and there are various results coming up
> (although not all are applicable, e.g. because they return a constant
> value). I'll include a few examples below, but the actual list is much
> longer:
>
> ```
> modes[char] = max(items, key=lambda x: x[1])
> modes[char] = max(items, key=?[1])  # proposed new syntax
>
> obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__")))
> obj = unwrap(obj, stop=hasattr(?, "__signature__"))
>
> s = re.sub(r"-[a-z]\b", lambda m: m.group().upper(), s)
> s = re.sub(r"-[a-z]\b", ?.group().upper(), s)
>
> members.sort(key=lambda t: (t[1], t[0]))
> members.sort(key=(?[1], ?[0]))
> ```
>
> Of course, there is no requirement to use `?` as the token, it could be
> any other character that's currently not used by Python, i.e. `$` or `!`
> would be possible too.
> ___
> 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/HADJG5L6ML7JRYKPRCSNJGWBY4NPG5NH/
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/SD4IUPNCTQMS25KJSVDO7WX45MYGYUYZ/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: A better math.factorial

2021-09-16 Thread Damian Shaw
Is there a reason you defined it as n * math.gamma(n), instead of
math.gamma(n+1)?

Damian (he/him)

On Thu, Sep 16, 2021 at 2:35 PM Jonatan  wrote:

> Currently, math.factorial only supports integers and not floats, whereas
> the "mathematical" version supports both integers and floats.
> I.e:
> ```
> import math
>
>
> def better_factorial(n):
> return n * math.gamma(n)
>
> print(math.factorial(10) == better_factorial(10))
> ```
>
> This ends up in `True`, as that's correct.
> However, `math.factorial(math.pi)` (for example, or any float)
> Ends up in `ValueError: factorial() only accepts integral values`.
> unlike `better_factorial(math.pi)` which would end up in 7.188082728976031.
>
> My proposal is to make another function for floats, or even use the same
> math.factorial function and check inside it whether the given input is an
> integer or a float object.
>
> I would like to hear your review.
> Jonathan.
> ___
> 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/HID2JPHO56Y2ZZ3MJGEGRDGPMJJLF5T3/
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/SNVF3TH256XAF4UCXH3LR4T76X2YPVND/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Template Literals for Python (easy and save creation of HTML)

2021-09-03 Thread Damian Shaw
I am not convinced of tying `backticks` for a single markup language.
Different markup languages presumably have different escape methods? Is
Python supposed to be explicitly an HTML based language like many of the
design choices of JavaScript?

It also seems like a lot to ask to introduce yet another way of quoting
strings which doesn't fit with the existing pattern of string quoting.
Python already has single quotes, double quotes, triple single quotes,
triple double quotes, and all of these can have an r or f placed in front
of them to modify their behavior.

I see you have a section on not using the "i" prefix, but I don't
understand the sentence "This is an handy feature, which would not work
reliably if there are two different prefixes". What is it trying to say?
What would not work reliably and why?

I would like to see this PEP have a section on handling security, this PEP
implies the Python standard library will safely escape HTML for you which
presumably has security implications? And a section on how it will be
updated when/if the HTML specification gets updated that may introduce new
ways HTML can/must be escaped. And a section on what are the valid versions
of HTML it supports? HTML5 only or does it explicitly support older
versions of HTML?

Damian (he/him)

On Fri, Sep 3, 2021 at 9:47 AM Thomas Güttler 
wrote:

> Some weeks ago I started the idea of Template Literals for Python:
>
> https://github.com/guettli/peps/blob/master/pep-.rst
>
> I just switched to a new company (descript.de) and diving into their
> context
> will need some time.
>
> This means I won't work on the Template Literals PEP.
>
> If you like the idea, then it would be great if you work on it.
>
> Regards,
>   Thomas
> ___
> 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/BZWBK2PFBFUXU5PEP7UZORHL23RQVHE4/
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/VTDQSJDUAERS3XMZ3772P6MFZ3TIGDS2/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Proposal: Python Native bindings for OpenAPI

2021-08-06 Thread Damian Shaw
In your code example it looks like FastAPI is making 1 HTTP request vs.
your library is making 3 HTTP requests? Or are there some missing lines? Or
am I missing something?

Also are you referring to https://github.com/pyopenapi/pyopenapi ? And if
so what would be the reasoning to pull something like this into the
standard library rather than leaving it as a third part library?

Damian (he / him)

On Sat, Aug 7, 2021 at 12:40 AM Vaideeswaran Ganesan 
wrote:

> I looked at the fastapi code.
>
> I actually want to avoid  get, post, put,  2xx, 4xx codes in the client
> portions of the code. (I don't think it's pythonic). And Fastapi seems to
> have them exactly the same.
> Look at how the code looks when you are using FastAPI and with my OpenAPI
> Native Bindings - below:
>
> === [Code using FastAPI]
> def test_create_item(): response = client.post( "/items/", headers={
> "X-Token": "coneofsilence"}, json={"id": "foobar", "title": "Foo Bar",
> "description": "The Foo Barters"}, ) assert response.status_code == 200
> assert response.json() == { "id": "foobar", "title": "Foo Bar",
> "description": "The Foo Barters",
> }.
>
> === [Code using pyopenapi - my proposal]
> def test_create_item():
> client = client('host', creds).connect('/')
> try: assert client.items.id == "foobar"
> assert client.items.title == "Foo Bar"
> assert client.items.description == "The Foo Barters"
> except AttributeError:
> print("Items does not exist!")
>
>
> On Fri, Aug 6, 2021 at 10:13 PM Gustavo Carneiro 
> wrote:
>
>> You may want to take a look at FastAPI[1], it already does more or less
>> what you ask for.
>>
>> There is no need for it to be part of the Python core, it's fine as it is
>> as a package.
>>
>> [1] https://fastapi.tiangolo.com/
>>
>> On Fri, 6 Aug 2021 at 17:39, Vaideeswaran Ganesan 
>> wrote:
>>
>>> OpenAPI (https://spec.openapis.org/oas/latest.html) is an emerging
>>> standard for defining RESTful interfaces.
>>> OpenAPI is supported by swagger - which provides tools to convert an
>>> OpenAPI spec into python code (for both backend as well as client).
>>>
>>> The proposition I have is to make OpenAPI native to python.
>>> Essentially, this involves some of the following:
>>> 1. OpenAPI provides definitions of objects, arrays, structures,
>>> primitive types, collections etc.
>>> 2. OpenAPI supports object creation (HTTPS POST), object modification
>>> (PUT), object deletion (DELETE) and object retrieval (GET).
>>> 3. OpenAPI also supports operations for collections (add to collection,
>>> remove from collection and modify collection)
>>> 4. OpenAPI also supports methods and allows parameters to be passed to
>>> these APIs.
>>>
>>> The Native Python implementation would load in OpenAPI specification and
>>> provide native Python experience as follows:
>>> 1. Primitive types are mapped to python primitive types
>>> 2. Objects and structures are treated as classes or dicts wrapped.  The
>>> field names in the Spec are accessible.
>>> 3. Arrays and Collections are mapped to python lists.
>>> 4. URLs are converted into object structure.
>>> 5.  Python inspection methods (__getattr__, __setattr__, __new__,
>>> __del__ and others) of this model is changed to manipulate the fetched
>>> objects dynamically
>>>
>>> Parts of this implementations are found in various places : sushy
>>> (OpenStack) etc.
>>> However, having a more organized approach would make life easier.
>>>
>>> Swagger has a tool that can generate the code.  But this means that
>>> every time a specification changes you need to ship a new python library.
>>> The methodology presented not require any addition python libraries -
>>> the tool can download from the REST end point.
>>>
>>> By making OpenAPI native to python, we would avoid cumbersome handling
>>> of request codes etc. and make it as you we are accessing native objects.
>>> I can provide more details and a reference implementation I am working
>>> on.
>>>
>>> Wanted to know if this is worthy to be submitted as PEP!
>>> ___
>>> 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/5DBYKAEXM2Z3UQZGORXMBQTBN22RQPLT/
>>> Code of Conduct: http://python.org/psf/codeofconduct/
>>>
>>
>>
>> --
>> Gustavo J. A. M. Carneiro
>> Gambit Research
>> "The universe is always one step beyond logic." -- Frank Herbert
>>
> ___
> 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/NVNZB2Y35HF6QRCI75USKZENI3HXNF3R/
> Code of Conduct: 

[Python-ideas] Re: Deprecate sum of lists

2021-06-18 Thread Damian Shaw
 Is there somewhere where you can use "*ab" but not "a ,b" currently in
Python?

On Fri, Jun 18, 2021 at 11:43 AM Mathew Elman 
wrote:

> I don't see how allowing
>
> [x, y for x in a]
>
> follows from allowing
>
> [*chunk for chunk in list_of_lists].
> ___
> 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/CTYGB5FE3EMJCH4JJJKGG3OIPTREBW6C/
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/GKAS3GJTZQL5WWEUX7VU6NGNJ5BUBQJ3/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: The Pattern Matching Wildcard Is A Bad Idea

2021-06-02 Thread Damian Shaw
> You'd expect code that runs in a shell to behave the same in a script,
and vice-versa. But, if `_` is both a variable (shell) and a keyword
(`match`), that 's not the case. You have to work around the problem, e.g.
by reaffecting `_`.

But the discrepancy here is not the match statement, it's that "_" in REPLs
doesn't behave like "_" in a script, if you are copying and pasting REPL
code to a script this is something you already need to take into account.

Also because REPLs have this feature only when the user doesn't bind to the
name "_":
>>> 5 * 2
10
>>> _
10
>>> _ = 5
>>> 5 * 2
10
>>> _
5

If the match statement didn't treat "_" as slightly special and bound the
match to "_" then it would break this feature of REPLs.

(apologies for mucking up the email addresses previously)

On Wed, Jun 2, 2021 at 11:35 AM Alexis Masson 
wrote:

> Yeah, that's it exactly.
>
> I see these two features - `_` as a joker in `match` statements and `_`as
> the last value produced by a shell - as incompatible, because you have to
> account for interferences between them, or face unexpected behaviors in
> code you run.
>
> I expect people to code like I do : first experiment a feature in a shell,
> then write a clean script that implements it cleanly. To debug that script,
> go back to the shell to run the script bit by bit, etc, etc.
> You'd expect code that runs in a shell to behave the same in a script, and
> vice-versa. But, if `_` is both a variable (shell) and a keyword (`match`),
> that 's not the case. You have to work around the problem, e.g. by
> reaffecting `_`.
> My fear is that most people (me included) will most likely forget this
> step when switching between a shell and a script.
>
>
> Le 02/06/2021 à 15:48, Damian Shaw a écrit :
>
> > The question is even more pressing in REPL, since there *is*
> necessarily such a variable !
>
> To clarify, your concern is that someone wants to use the match statement
> in the REPL and use "_" to match against the last return without needing to
> workaround with something like "last = _" and then matching against "last"?
>
>
>
> On Wed, Jun 2, 2021 at 9:30 AM Alexis Masson 
> wrote:
>
>> Hey everyone,
>>
>> I meant to say, I agree with the two of you, actually. `_` as a variable
>> name is terrible, but it *can* be used all the same ; on the other hand,
>> wildcards should not be legitimate variable names, to prevent
>> misunderstandings / accidents / bugs.
>>
>> Had I taken part in the discussion aroud pattern matching, I would have
>> liked the `else` syntax better : having a special syntax for special cases
>> seems clearer, cleaner, and safer.
>> Another option that comes to mind is using `*` as the wildcard. There is
>> already a precedent for using `*` alone, e.g. in `import` statements. In
>> this case, it means "import everything from this module", as opposed to
>> listing the items you need. I can easily see the parallel with `match`
>> statements, thus making it intuitive to learn and use this new syntax.
>>
>> Anyway, yes, `_` as joker has flaws, the biggest one being to be a
>> resolvable variable name ; what is the expected behaviour when running a
>> script that has (even accidentally) a viariable named `_` ? The question is
>> even more pressing in REPL, since there *is* necessarily such a variable
>> !
>>
>> I guess it's too late to change anything, though, so we'll have to get
>> used to it...
>>
>> From https://docs.python.org/3.10/whatsnew/3.10.html:
>>
>> def http_error(status):
>> match status:
>> case 400:
>> return "Bad request"
>> case 404:
>> return "Not found"
>> case 418:
>> return "I'm a teapot"
>> case _:
>> return "Something's wrong with the Internet"
>>
>> The wildcard idea looks just wrong and confusing. What if I want to use
>> it as a variable and match against it like _ = 504? This is how it should
>> be done:
>>
>> def http_error(status):
>> _ = 504
>> match status:
>> case 400:
>> return "Bad request"
>> case 404:
>> return "Not found"
>> case 418:
>> return "I'm a teapot"
>> case _:
>> return "Gateway Timeout"
>> else:
>> return "Something's wrong with the Internet"
>>
>>
>> Don't do that

[Python-ideas] Re: Introduce constants in Python (constant name binding)

2021-05-25 Thread Damian Shaw
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?

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.
>
> --
> ~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 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/MM6WSMJFFDXEVNUFQ6DSAM5HGLOJ3MYR/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: New Idea: A safe keyword to execute the following statement in a failsafe mode.

2021-05-23 Thread Damian Shaw
FYI,

Something very similar already exists in the standard library,
contextlib.suppress:
https://docs.python.org/3/library/contextlib.html#contextlib.suppress

It makes a nice 2+ liner for a lot of situations:

with suppress(Exception):
...

Seems more flexible than OPs keyword suggestion as you can fit an entire
block of code in there, not just a single expression. And it's quite
semantically expressive.

Damian
(he/him)

On Sun, May 23, 2021 at 9:28 AM Ricky Teachey via Python-ideas <
python-ideas@python.org> wrote:

> I think you can already do all of this with a custom exception-swallowing
> decorator function.
>
> Something like this:
>
> from functools import wraps
>
> def swallow(*exceptions, default=Exception, result=None):
> if not exceptions:
> exceptions = Exception,
> def decorator(func):
> @wraps(func)
> def wrapped(*args, **kwargs):
> try:
> return func(*args, **kwargs)
> except exceptions:
> return result
> return wrapped
> return decorator
>
> Then just write:
>
> @swallower()
> def some_func():
> log_to_telegram('This is a not important message. It's okay even if
> it isn\'t delivered.')
>
> For divide by zero errors you need to put the division operation in a
> lambda function:
>
> safe_divide = swallow(DivideByZero, result=0)
> division = safe_divide(lambda: a/b)
>
> I didn't test any of this but it should be working.
>
> On Sun, May 23, 2021, 8:54 AM Shivam Saini  wrote:
>
>> Sometimes, we need to execute a statement, which might throw an exception
>> and we want to return None if it causes an exception. In short, we want to
>> run that command as failsafe mode, so that it doesn't cause abnormal
>> termination in case of any exception.
>>
>> *Approach till now:*
>>
>> def log_to_telegram(text):
>> ''' Suppose you want to send some log to some telegram channel using
>> telegram bot api. It might raise Network Error, or Invalid Bot token error.
>> '''
>> send_message(CHANNEL, BOT_TOKEN, TEXT) # Suppose send_message is a
>> function wrapper for telegram bot api.
>>
>> def some_func():
>> try:
>> log_to_telegram('This is a not important message. It's okay even
>> if it isn\'t delivered.')
>> except:
>> pass
>> # Next work
>>
>> *Suggested approach:*
>>
>> # consider the same log_to_telegram function as defined in previous
>> example
>>
>> def some_func():
>> safe log_to_telegram('This is a not important message. It's okay even
>> if it isn\'t delivered.')
>> # safe keyword ensures that it raises no exception and the process
>> isn't terminated even if log_to_telegram function raises an exception.
>>
>> *Other examples:*
>>
>> *1. By default, it will return None.*
>> *Example: *
>> try:
>>file = open('some_file')
>>except:
>>file = None
>> *Can be rewritten as:*
>>file = safe open('some_file')
>>
>> *2. We can provide a return value explicitly which should be returned in
>> case of some exception.*
>> *Example: *
>> try:
>>division = a/b
>>except:
>>division = 0
>> *Can be rewritten as:*
>> division   = safe(0) a/b
>>
>> *3. We can set what exceptions we want to be 'safed'.*
>> *Example: *
>> try:
>>element = some_list[index]/divisor
>>except ZeroDivisionError:
>>element = 0  # It will make element zero if divisor is zero,
>> but it will not except IndexError in case index is out of range for
>> some_list
>> *Can be rewritten as:*
>>element = safe(0, ZeroDivisionError) some_list[index]/divisor
>>
>> *I think this keyword should be there in python, it will make code short
>> and readable. *
>> ___
>> 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/5SEDN6AUM7LZPZZJJZ3RMAKHKHN6N665/
>> Code of Conduct: http://python.org/psf/codeofconduct/
>>
>> ___
> Python-ideas mailing list -- python-ideas@python.org
> To unsubscribe send an email to python-ideas-le...@python.org
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at
> https://mail.python.org/archives/list/python-ideas@python.org/message/ORKXAAH2EZFYHJMVU74H5R6BSJVMMER7/
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/D5SCJFV3ASC5VJTCQ2ENGCVGALQCOXGT/

[Python-ideas] Re: Accepting a function argument of a particular type specified by the user

2021-04-25 Thread Damian Shaw
Typeguard provides this functionality:
https://typeguard.readthedocs.io/en/latest/userguide.html

It's not perfect but that's because runtime type hints have lots of
restrictions on what can be reasoned about them. But for simple and common
cases it works very well.

--
Damian (he / him)

On Sun, Apr 25, 2021 at 9:38 AM Richard Damon 
wrote:

> On 4/25/21 9:09 AM, Shreyan Avigyan wrote:
> > Think it like this. We have this code in Python :-
> >
> > def add(a, b):
> > return a + b
> >
> > Here we are taking two arguments a, b and then returning a + b. But we
> can pass in instance of any class like str, int, float, dict, user-defined
> class, etc. But we only want to add int here. Here we can modify it to be,
> >
> > def add(a, b):
> > if type(a) == int and type(b) == int:
> > return a +b
> > raise Exception("Error")
> >
> > In this example it's pretty easy to check if the arguments are int. But
> in real world programs as the functions become bigger and bigger it's very
> difficult to check arguments using an if statement.  Therefore why not let
> the user specify what parameter types are gonna be? Like,
> >
> > def add(int a, int b):
> > return a + b
> >
> > If instance of a different class is passed in then raise a TypeError
> perhaps? If parameter types are not given then let the parameter accept any
> kind of class instance.
> >
> > This kind of functionality will minimize a lot of if statements related
> to parameter types and arguments.
> >
> > Thanking you,
> > With Regards
>
>
> Well, in Python with type annotations that would be spelled:
>
> def add(a: int, b: int):
>
> return a + b
>
> but the one difference is that, at least by default, that requirement is
> advisorary only. You can run a static type checker like mypy at it will
> see if it can deduce a case where you pass a non-int to the function.
>
>
> You could also import a module into your module that will actually do
> the check at run-time (I don't know of one, but there probably is one)
> maybe needing the function to be decorated to request the type checking.
>
> --
> Richard Damon
>
> ___
> 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/7DCIKCAQOD7FLC3SKYYGBDEHUOYBU472/
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/GRKV76INWYQXSQ3DTSJFIXH4GLPY5UB6/
Code of Conduct: http://python.org/psf/codeofconduct/