[Python-ideas] Re: [dataclasses] add a NON_FIELDS sentinel after which all attributes are ignored.

2023-06-22 Thread Jelle Zijlstra
El jue, 22 jun 2023 a las 8:22, Randolf Scholz ()
escribió:

> Dataclasses should provide a way to ignore a type hinted attributes, and
> not consider them as fields.
>
> For example, some attributes might be derived during `__post_init__` from
> the values of the fields or other variables.
>
> If one wants to still type hint these attributes, one has to awkward
> workarounds to avoid having dataclass interpret them as fields. (
> https://stackoverflow.com/questions/76532816)
>
> I propose `NON_FIELDS` sentinel, analogous to `KW_ONLY`. (alternative name
> suggestions welcome). when writing a dataclass, all attributes after this
> sentinel are ignored and not considered fields.
>
> ```
> @dataclass
> class Foo:
> field0: int
> field1: int
>
> _: KW_ONLY
>
>fieldN: int
>
> _: NON_FIELDS
>
> attr0: int   # @dataclass will ignore this type hint.
>

How is this different from `attr0: int = field(init=False)`?


> ```
>
> Additionally one could consider adding an `attribute` typing construct,
> such that `attr0: attribute[int]` would mark it as a non-field attribute.
> ___
> 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/P67URFV2JJRFD6J5TXD44EEBO4IRTEYF/
> 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/HS5E5XNHKLO47Q6UPF5QVUCIK2FR6VSF/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Keyword argument support for exec/eval?

2023-06-07 Thread Jelle Zijlstra
I would support allowing the globals and locals arguments to exec() to be
passed as keyword arguments. Open an issue on
https://github.com/python/cpython and if no other core devs object, we can
fix this in 3.13.

The actual code change would be very small thanks to Argument Clinic.

El mié, 7 jun 2023 a las 5:55, Raphael Gaschignard ()
escribió:

> I have searched for chatter about this in the past, and realize that
> churning about on this topic might be a bit of a time waster, but what
> would be required to make eval and exec be able to take keyword arguments?
>
> Explaining exec and eval, and not being able to use kwargs to establish an
> ordering (especially when the docs talk about defaults) is not great IMO.
>
> Has there been discussion in the past on when adding kwarg support for
> existing functions becomes a thing that patches are accepted for?
> ___
> 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/AD37KVC4CP4HQD4D7VUJTCWSP4LKEZYB/
> 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/7EJ57WXPQRZSMNJUHT5SBFQZDSRDUU7P/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Protocols Subclassing Normal Classes

2023-04-24 Thread Jelle Zijlstra
The formal term for that is intersection types. There is a long-standing
thread about that at https://github.com/python/typing/issues/213; there are
some uses but the feature would greatly complicate the type system, so it's
not clear that it's worth adding.

At this point, what Intersection needs is someone to champion the proposal
and write a PEP.

El lun, 24 abr 2023 a las 6:21, Mathew Elman ()
escribió:

> Rather than changing Protocols and affecting lots of users, it seems like
> was you really want is a generic class that is the "and" to Union's "or"?
> e.g.
>
> def foo(thing: All[Thread, SupportsStop]):
> ...
>
> which seems reasonable. If that appeals to you, then you probably want to
> raise that on the typing thread?
> ___
> 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/JV3OYN5LXNMHBOT5RGEFHXSQYFKNB2EB/
> 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/IRDVK4B6K3QPIZAZ35YKVCFFAYA72WJM/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: new PEP: implementation independent native code invocation and data exchange ABI standard (not sure if accurate)

2023-04-23 Thread Jelle Zijlstra
At the Language Summit a few days ago we discussed this problem. I wasn't
involved in this discussion, but it's a hard one to solve.

You may be interested in HPy (https://hpyproject.org/), which aims to
provide what you are looking for.

El dom, 23 abr 2023 a las 6:18, Evan Greenup via Python-ideas (<
python-ideas@python.org>) escribió:

> Dear All
>
> Python is a "glue" language, its dynamic nature has programming advantage
> and performance disadvantage.
> The best way to use Python is write Python code for high-level stuff and
> use native programming language like C, Rust, Zig, V for low level stuff.
> Currently, there is library like PyO3 and so on.
> However there is a lot of limitation in those library.
>
>1. The "FFI" library is implementation specific. For example, PyO3, it
>highly depend on specific version of CPython. If you use a different
>version of CPython, there is some work for you to do. If you don't use
>CPython, for example use another Python Implementation, This framework may
>not work.
>2. The project structure is rigid. When using something like PyO3. you
>must make your project structure following certain pattern, then finally
>produce a complete wheel package. The majority Python programmer does not
>write a whole Python project for a installable package and pack it up then
>install it. They are edit Python source file iteratively and run it
>locally.
>3. It is really ridiculous when you want to stick some item on the
>wall. You need to totally redesign this item and manufacture a new item to
>fit the glue you are going to use. As a glue language, Python should be
>designed to glue other native programming language as a feature of Python
>programming language itself not the tricks of certain variant of
>implementation.
>
> It would be nice to add the feature in Python Standards (no matter what
> implementation is used) to satisfy the following capabilities:
>
>- The interface is universal across all variant and version of Python
>implementation (There might be protocol version update and may not
>backward-compatible, but it is not bounded with Python implementation). The
>overall effect is in some extent like JSON, but it is not a structured
>string, It is a lively data structure with in-memory representation, they
>are unified no matter what Python variant is used and what low level native
>language is used.
>- This mechanism is transparent to users, there is modules in standard
>library to support it. If user want, they can design a toy native
>programming language, and use Python to write a compiler for it. Then write
>a module with custom language then compile and import it. This mechanism
>provide user with maximum flexibility.
>- almost zero-cost abstraction. Even if it not depend on CPython
>tricks. But the central idea of this mechanism is still the dynamic linking
>feature provided by operating system. The detailed format will be slightly
>different. It doesn't introduce new stuff in nature. It doesn't spawn new
>process, nor launch a VM, and nor I/O operations is involved. It just make
>some basic data representation conversion and invoke the method in dynamic
>library.
>
> This is just a raw idea. If it is valuable, it can take a discussion and
> make further steps.
>
> Thanks
> ___
> 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/R2NBDZHCCTJNRN27XP7PY7QLKDLYKSAW/
> 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/WZKFVNEIZHZLTE4UPAHZ4F4SHT3JVNXN/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Confusing naming of Optional type should be changed

2022-07-01 Thread Jelle Zijlstra
El jue, 30 jun 2022 a las 22:19, Stephen J. Turnbull (<
stephenjturnb...@gmail.com>) escribió:

> nveric...@gmail.com writes:
>
>  > I accidentally created another thread in python-dev as I mentioned
>  > above, but ideally Optional and Union should both be deprecated and
>  > phased out for the new syntax.
>
> I think a formal deprecation is a bad idea.  An annotation is an
> object, which has a type.  Both the object and the type are going to
> be visible to users.  We don't want there to be warnings about them
> forever, and Python as a rule does not formally deprecate working code
> that is expected to continue to work indefinitely.
>
> I suspect that it would be difficult to get a stylistic deprecation
> into PEP 8 (IIRC type annotations are still not allowed in stdlib code
> so it would be considered out of scope), but you could try lobbying
> the maintainers of linters.
>
> BTW, I disagree with your arguments that Optional and Union are
> misleading names that can be easily misunderstood, especially in the
> usual context of formal arguments in function definitions.  The
> suggestion of "Noneable" takes the Pythonic implementation of optional
> arguments (by defaulting to None) too seriously, at the expense of the
> syntactic intention: an argument that may be omitted.  Among other
> things, very frequently 'None' is *not* an allowed value in the body
> of the function, some other value is immediately substituted (and PEP
> 671 explicitly tries to automate this process for the common case of a
> mutable default that should be constructed at call time, so that even
> the idiomatic "if arg is None" statement is left out).
>
> "Optional" is the normal term used for such arguments, "union" is the
> technical term for types composed of being either this or that type.
> If you need to know any more than that about those types, you're going
> to have to study up no matter what terms are used.  That's just the
> nature of using natural language words to name things that have a
> precise definition and implementation in software.  Study is required.
>

In fact, `typing.Optional` means that something can be None, *not* that it
is an optional argument.

In other words:

def f(x: Optional[str], y: int = 0): ...

f(x=None)  # allowed
f()  # not allowed (x is omitted)
f(x="", y=None)  # not allowed (y cannot be None)

That's the opposite of what you describe, so really you're making an
argument against the use of the Optional term.


>
> Steve
> ___
> Python-ideas mailing list -- python-ideas@python.org
> To unsubscribe send an email to python-ideas-le...@python.org
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at
> https://mail.python.org/archives/list/python-ideas@python.org/message/LELXP5FPJZWF36NR423ZLVOHGXQTUVKL/
> 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/7CGTM6CNP3QHB6UXZMTP3KKZ5D47YT42/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Confusing naming of Optional type should be changed

2022-06-30 Thread Jelle Zijlstra
El jue, 30 jun 2022 a las 10:46,  escribió:

> (I apologize in advance if I've posted anything incorrectly before, I
> believe I might have sent this in python-dev instead but not sure as it's
> not appearing in the posts for my account).
>
> I am aware this is clarified in the Python documentation for the typing
> module but I and others have thought the naming of Optional is still quite
> confusing by itself.
>
> "Note that this is not the same concept as an optional argument, which is
> one that has a default. An optional argument with a default does not
> require the Optional qualifier on its type annotation just because it is
> optional." - typing.Optional docs
>
> Google defines optional as this, "available to be chosen but not
> obligatory."
>
> Pretend we have a function like this:
> def test_func(param: Optional[str]) -> None:
> ...
>
> The argument param is typed as Optional[str] meaning Union[str, None] or
> str | None. Optional here if we follow the definition above, basically
> means it can be str but not required or obligated to be that type. See the
> problem with the naming? This is a function where param can be None or str,
> not just it can be str but not obligated. Some interpretations may think
> optional means left to one's choice as well. The docs even have to clarify
> the use of Optional with typing because of this confusion.
>
> I believe this has been proposed before (not sure) but something like
> Nullable or Noneable (not sure about naming) would make much more sense in
> the context of typing.
> def test_func(param: Noneable[str]) -> None:
> ...
>
> It also would work and still make sense if there is a default value for
> the argument:
> def test_func(param: Noneable[str] = None) -> None:
> ...
>
> def test_func(param: Noneable[str] = "hello world") -> None:
> ...
>


This problem has already been solved: in Python 3.10, thanks to PEP 604,
you can write `str | None` instead of `Optional[str]`.


> ___
> 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/GV3ZHUYFAO2GM7PP4UX4JEMBEBOHRNQW/
> 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/DRQWYCGPAEBIIH3DTALTMAJVKAEL53NL/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Generalized deferred computation in Python

2022-06-26 Thread Jelle Zijlstra
El sáb, 25 jun 2022 a las 13:44, Chris Angelico ()
escribió:

> On Sun, 26 Jun 2022 at 04:41, Brendan Barnwell 
> wrote:
> > In contrast, what I would want out of deferred evaluation is
> precisely
> > the ability to evaluate the deferred expression in the *evaluating*
> > scope (not the definition scope) --- or in a custom provided namespace.
> >   Whether this evaluation is implicit or explicit is less important to
> > me than the ability to control the scope in which it occurs.  As others
> > mentioned in early posts on this thread, this could complicate things
> > too much to be feasible, but without it I don't really see the point.
>
> A custom-provided namespace can already be partly achieved, but
> working in the evaluating scope is currently impossible and would
> require some major deoptimizations to become possible.
>
> >>> expr = lambda: x + y
> >>> expr.__code__.co_code
> b't\x00t\x01\x17\x00S\x00'
> >>> ns = {"x": 3, "y": 7}
> >>> eval(expr.__code__, ns)
> 10
>
> This works because the code object doesn't have any locals, so the
> name references are encoded as global lookups, and eval() is happy to
> use arbitrary globals. I say "partly achieved" because this won't work
> if there are any accidental closure variables - you can't isolate the
> lambda function from its original context and force everything to be a
> global:
>
> >>> def f(x):
> ... return lambda: x + y
> ...
> >>> expr = f(42)
> >>> eval(expr.__code__, ns)
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: code object passed to eval() may not contain free variables
>
> The mere fact that there's a local variable 'x' means that you can't
> compile the expression 'x + y'. So maybe there'd need to be some weird
> trick with class namespaces, but I'm really not sure what would be
> worth doing.
>
> Note that in Python 3.11 exec (but not eval) gains the ability to pass an
explicit closure:

>>> def f(x):
... return lambda: print(x + y)
...
>>> l = f(1)
>>> exec(l.__code__, {"y": 3}, closure=(types.CellType(2),))
5

This doesn't quite solve the problem being discussed here, but it may help.

This was added in https://github.com/python/cpython/pull/92204. We didn't
add it to eval() because there was no use case at the time, but it would be
easy to add the same support to eval() 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/7IPM4KFLZGTQDMOJW6VKE6YP2U2BTQLB/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Expand type coverage in cpython implementation

2022-03-16 Thread Jelle Zijlstra
El mié, 16 mar 2022 a las 3:58, Jared Crawford ()
escribió:

> Hi all,
>
> I recently noticed that stdlib functions often don't have type hints. Is
> there a technical reason why typing isn't more widespread in the cpython
> implementation?

Mostly there hasn't been agreement to add them. See
https://discuss.python.org/t/type-annotations-in-the-standard-library/7309
for a previous discussion.


> As a developer, it'd be great if I didn't have to wrap many of my stdlib
> calls in casts to make mypy happy.

Mypy uses standard library types from the typeshed repo (
https://github.com/python/typeshed) and doesn't look at the stdlib source
code. If any of the typeshed types are incomplete, please report an issue
there.


> Please let me know if there's a more appropriate channel for this
> discussion. I tried looking through the mailing list archives and github
> issues, but I couldn't find the answer to this.
>
> Best,
> Jared
> ___
> 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/3W43OKUUPVECIJMRTH7XVPFZCG7GFOVE/
> 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/B6K7ULDFPUMPSLIG2SAK6LVP4JH7JXPL/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Syntax proposal of for..in..if in regular for loops

2022-03-07 Thread Jelle Zijlstra
El lun, 7 mar 2022 a las 19:57, Christopher Barker ()
escribió:

> On Mon, Mar 7, 2022 at 3:43 PM Chris Angelico  wrote:
>
>> On Tue, 8 Mar 2022 at 10:39, Jelle Zijlstra 
>> wrote:
>> >
>> >
>> >
>> > El lun, 7 mar 2022 a las 15:35, Chris Angelico ()
>> escribió:
>> >but python-ideas is 100% shooting ideas to pieces.
>
>
> 100% really? Maybe my sense of time is blurred, but some ideas do make it
> through.
>
> PEP 618 (zip(strict=True)) and PEP 616 (str.removeprefix) originated on
python-ideas and were accepted.
___
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/QIW26KTHWLFG5OJZO5WSX73MOMVKXUUP/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Syntax proposal of for..in..if in regular for loops

2022-03-07 Thread Jelle Zijlstra
El lun, 7 mar 2022 a las 15:35, Chris Angelico ()
escribió:

> On Tue, 8 Mar 2022 at 10:20, Brendan Barnwell 
> wrote:
> >
> > On 2022-03-06 14:43, Chris Angelico wrote:
> > > This keeps happening. All the successful ideas seem to happen
> > > elsewhere, notably on typing-sig.
> >
> > You seem to see that as a positive thing, but I would be happier
> if
> > fewer typing-related changes made it in.
> >
>
> I'm not sure whether it's positive or not. All I can see is that
> changes get proposed on typing-sig and actually make it into the
> language, but changes that get proposed on python-ideas are invariably
> shot down in flames, no matter how good or bad. I do NOT believe that
> every idea on typing-sig is good and that every idea on python-ideas
> is bad, so what is it that makes typing-sig actually successful in
> refining ideas into usable form that python-ideas is failing at?
>
> An important point here is that most typing changes aren't language
changes, but just new things added to typing.py. Getting a library function
changed or added is a lot easier than adding new syntax. Besides, typing is
much younger than the language, so there is more remaining opportunity for
useful additions. And there are plenty of ideas that get proposed around
typing that don't make it to PEPs.


> ChrisA
> ___
> Python-ideas mailing list -- python-ideas@python.org
> To unsubscribe send an email to python-ideas-le...@python.org
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at
> https://mail.python.org/archives/list/python-ideas@python.org/message/OP6NSGLPJM4IFH3RH4S5M6MKIRMTSJTF/
> 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/3EGHMBKTEINOV7YKZKRG6KRXYSJEOYAJ/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Creating a class template file generator inside Python language

2022-02-16 Thread Jelle Zijlstra
Are you aware of https://docs.python.org/3.10/library/dataclasses.html?
That essentially provides a way to generate the boilerplate without having
to put it all in your code.

El mié, 16 feb 2022 a las 5:20, Avanish Gupta ()
escribió:

> Thanks for the previous mail.
> I would like to highlight the value my thought offers to the developers.
> They often have to write classes while writing a module. In the class, they
> are supposed to write classes and objects. In a class, typically the
> attributes are private, and we have getters and setters to access and
> modify them. My thought is to automate the process of creating such class
> files with command line.
> For this, I have made my initial attempt to create a module that does so.
> Here is a short video in which I am demonstrating it.
> I am also attaching the details of my terminal to get a bit of more
> details.
>
> I am looking forward to hearing from you if I should work on integrating
> it within the Python Language features, or I should go some other way
> round, or this is not a very useful tool for many people.
>
> *avanishcodes@avanishcodes*:*~*$ echo "No Student.py file here"
> No Student.py file here*avanishcodes@avanishcodes*:*~*$ ls*Academics*  
> *Documents*  *node_modules*   *Pictures*  *snap**Videos**bin* 
>*Downloads*  package.json   *Projects*  Student.py*Desktop**Music* 
>  package-lock.json  *Public*
> *Templates**avanishcodes@avanishcodes*:*~*$ rm Student.py 
> *avanishcodes@avanishcodes*:*~*$ ls*Academics*  *Documents*  *node_modules*   
> *Pictures*  *snap**bin**Downloads*  package.json   *Projects* 
>  *Templates**Desktop**Music*  package-lock.json  *Public*
> *Videos**avanishcodes@avanishcodes*:*~*$ pip install classgen
> Requirement already satisfied: classgen in 
> ./.local/lib/python3.8/site-packages (0.0.7)*avanishcodes@avanishcodes*:*~*$ 
> python3 -m classgen Student member1,member2,member3,member4,member5,member6
> Class Student generated successfully.*avanishcodes@avanishcodes*:*~*$ cat 
> Student.py
> #(class) Student
> class Student:
> """
> This class is used to represent a Student.
>
> Attributes:
> member1: The member1 of the Student.
> member2: The member2 of the Student.
> member3: The member3 of the Student.
> member4: The member4 of the Student.
> member5: The member5 of the Student.
> member6: The member6 of the Student.
>
> Methods:
> get_member1(self): Gets the member1 of the Student.
> get_member2(self): Gets the member2 of the Student.
> get_member3(self): Gets the member3 of the Student.
> get_member4(self): Gets the member4 of the Student.
> get_member5(self): Gets the member5 of the Student.
> get_member6(self): Gets the member6 of the Student.
> set_member1(self, member1): Sets the member1 of the Student.
> set_member2(self, member2): Sets the member2 of the Student.
> set_member3(self, member3): Sets the member3 of the Student.
> set_member4(self, member4): Sets the member4 of the Student.
> set_member5(self, member5): Sets the member5 of the Student.
> set_member6(self, member6): Sets the member6 of the Student.
> """
>
> _member1: None
> _member2: None
> _member3: None
> _member4: None
> _member5: None
> _member6: None
>
> def __init__(self, member1, member2, member3, member4, member5, member6):
> """
> Initializes a Student object.
>
> Params:
> member1: The member1 of the Student.
> member2: The member2 of the Student.
> member3: The member3 of the Student.
> member4: The member4 of the Student.
> member5: The member5 of the Student.
> member6: The member6 of the Student.
> """
> self._member1 = member1
> self._member2 = member2
> self._member3 = member3
> self._member4 = member4
> self._member5 = member5
> self._member6 = member6
>
> def get_member1(self):
> """
> Gets the member1 of the Student.
>
> Returns:
> get_member1: The member1 of the Student.
> """
> return self._member1
>
> def get_member2(self):
> """
> Gets the member2 of the Student.
>
> Returns:
> get_member2: The member2 of the Student.
> """
> return self._member2
>
> def get_member3(self):
> """
> Gets the member3 of the Student.
>
> Returns:
> get_member3: The member3 of the Student.
> """
> return self._member3
>
> def get_member4(self):
> """
> Gets the member4 of the Student.
>
> Returns:
> get_member4: The member4 of the Student.
> """
> return self._member4
>
> def get_member5(self):
> 

[Python-ideas] Re: mimetypes.guess_type should not return deprecated mimetype application/x-javascript

2022-01-18 Thread Jelle Zijlstra
Perhaps there should be a guess_all_types() function in addition to
guess_type() that returns all possible types, so that the user can select
the type they want using any criterion. This would be nicely symmetrical
with the existing guess_extension and guess_all_extensions functions.
___
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/EV5RVLS4JC3XPYKWCJEFMLDTUVHOPU4Z/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Revisiting a frozenset display literal

2022-01-17 Thread Jelle Zijlstra
El lun, 17 ene 2022 a las 7:11, Steven D'Aprano ()
escribió:

> On Mon, Jan 17, 2022 at 11:18:13PM +0900, Inada Naoki wrote:
> > On Mon, Jan 17, 2022 at 8:49 PM Steven D'Aprano 
> wrote:
> > >
> > > On Mon, Jan 17, 2022 at 08:04:50PM +0900, Inada Naoki wrote:
> > >
> > > > Name lookup is faster than building set in most case.
> > > > So I don't think cost to look name up is important at all.
> > >
> > > But the cost to look up the name is *in addition* to building the set.
> > >
> >
> > I meant it is negligible so we can just ignore it while this discussion.
>
> On my computer, the name lookup is almost a quarter of the time to build
> a set:
>
> [steve ~]$ python3.10 -m timeit "frozenset"
> 1000 loops, best of 5: 24.4 nsec per loop
> [steve ~]$ python3.10 -m timeit "{1, 2, 3, 4, 5}"
> 200 loops, best of 5: 110 nsec per loop
>
> and about 10% of the total time:
>
> [steve ~]$ python3.10 -m timeit "frozenset({1, 2, 3, 4, 5})"
> 100 loops, best of 5: 237 nsec per loop
>
> If I use a tuple instead of the set, it is about 12% of the total time:
>
> [steve ~]$ python3.10 -m timeit "frozenset((1, 2, 3, 4, 5))"
> 200 loops, best of 5: 193 nsec per loop
>
> So not negligible.
>
> That is in the global scope, which will be much slower than a local scope.
Global builtins do a hash table lookup; local lookups just follow a
pointer.

>
>
>
> --
> Steve
> ___
> Python-ideas mailing list -- python-ideas@python.org
> To unsubscribe send an email to python-ideas-le...@python.org
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at
> https://mail.python.org/archives/list/python-ideas@python.org/message/YL2DW3GDYQZS4HEOIUG6T25HAUL3DGAQ/
> 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/EOAX3UEMBOCNWULBV2K54TUNFMWTT2XM/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: PEP Idea: Better return type annotation syntax

2022-01-06 Thread Jelle Zijlstra
On Thu, Jan 6, 2022 at 10:44 PM Tushar Sadhwani <
tushar.sadhwani...@gmail.com> wrote:

> With the recent submission of [PEP 677][1], I was reminded of an idea I
> had with function annotation syntax since the very beginning:
>
> why not let me write:
>
> ```python
> def f() -> tuple[int, str]:
> return 42, 'foo'
> ```
>
> as:
>
> ```python
> def f() -> (int, str):
> return 42, 'foo'
> ```
>
> Is there any inherent reason for this, other than that it isn't an actual
> "type"?

I like this too. A practical issue is that list[(a, b)] and list[a, b] look
the same to the compiler, but they would mean very different things. It's
not obvious how to fix this in a backward-compatible way.

>
>
> I think it looks much cleaner, and if there isn't any drawbacks to adding
> this syntax, I'd love to work on bringing this to life.
>
> [1]: https://www.python.org/dev/peps/pep-0677/
> ___
> 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/NLZOBGSJT3A7KVSZVIHCQBOGKZ2E7AI2/
> 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/AXYLQCVEW5MBV7T7SYER3DPLWPH7BXSB/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: extending ast.parse with some lib2to3.pytree features

2021-11-22 Thread Jelle Zijlstra
El dom, 21 nov 2021 a las 14:35, Peter Ludemann ()
escribió:

> Neil Girdhar wrote:
> > I wish this had gotten more attention! :)
>
> I wonder what the various projects are doing to handle the latest version
> of Python, if they need a parse tree with whitespace information. (The
> projects I know of are yapf, black, mypy, pytype, kythe -- are there
> others?)
>
mypy just uses the ast module; it doesn't care about whitespace.

For Black, we're using a patched version of lib2to3. Batuhan kindly
contributed a patch that extends our version of lib2to3 to mostly parse the
match statement (https://github.com/psf/black/pull/2586).

And I had never heard of kythe, so I am going to look that up now.


>
> ast.parse() has an option `type_comments`, so certain kinds of comments
> are handled -- I wonder how much work it would be to extend this to handle
> all whitespace?
> ___
> 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/747HHPVSNK6TCSOZHJHUEUDX2GKQROKN/
> 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/LETCFPQEKCRPRJTXZEMZIDGWKSR7LVDK/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Adding pep8-casing-compliant aliases for the entire stdlib

2021-11-11 Thread Jelle Zijlstra
El jue, 11 nov 2021 a las 5:41, Matt del Valle ()
escribió:

> So I was reading the docs for the `threading` module and I stumbled upon
> this little note:
>
> Note:
>
> In the Python 2.x series, this module contained camelCase names for some
> methods and functions. These are deprecated as of Python 3.10, but they are
> still supported for compatibility with Python 2.5 and lower.
>
>
> And it got me thinking.
>
> Given that there is some precedent, would it be feasible to make a
> concerted effort to add aliases across the board for all public-facing
> stdlib types and functions that don't follow pep8-recommended casing?
>
>
> Like most people commenting here, I'm not excited about this proposal. I
have some concrete experience to add: In the threading module, we did
rename a number of methods to snake_case for Python 3, but kept the old
camelCase names around. I worked on explicitly deprecating some of those
names (https://bugs.python.org/issue43723), because the documentation
already claimed they were going to be deprecated, and in retrospect I don't
feel like that was a very useful contribution. It just introduces churn to
a bunch of codebases and makes it harder to write multiversion code.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/MMODNBXXVPGISCID2LND32B6TO6ZRK6B/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Syntax for late-bound arguments

2021-10-23 Thread Jelle Zijlstra
El sáb, 23 oct 2021 a las 12:57, Guido van Rossum ()
escribió:

> I like that you're trying to fix this wart! I think that using a different
> syntax may be the only way out. My own bikeshed color to try would be `=>`,
> assuming we'll introduce `(x) => x+1` as the new lambda syntax, but I can
> see problems with both as well :-).
>
> In the PEP's example:

def bisect_right(a, x, lo=0, hi=>len(a), *, key=None):

This reads to me like we're putting "hi" into "len(a)", when it's in fact
the reverse. What about:

def bisect_right(a, x, lo=0, hi<=len(a), *, key=None):

Another option (going back to Chris's original suggestion) could be:

 def bisect_right(a, x, lo=0, hi:=len(a), *, key=None):

Which is the same as the walrus operator, leaning on the idea that this is
kind of like the walrus: a name gets assigned based on something evaluated
right here.

Bikeshedding aside, thanks Chris for the initiative here! This is a tricky
corner of the language and a promising improvement.
___
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/B6IDAKCVS7JENMGYC7ZYCK7SHVCBVPEI/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Structure Pattern for annotation

2021-10-15 Thread Jelle Zijlstra
El vie, 15 oct 2021 a las 14:42, Abdulla Al Kathiri (<
alkathiri.abdu...@gmail.com>) escribió:

> I don’t understand why tuple structure is not supported already. It makes
> reading the function signature a breeze and very natural. You can also do
> it without parentheses which mimics the return of multiple objects often
> seen in functions(def func(*args: int) -> str, [int])
>
> I brought this up before and one issue is that it's hard to distinguish
between a tuple used as a type parameter and multiple type parameters:

GenericClass[(A, B)]  # parameterized by the type Tuple[A, B]
GenericClass[A, B]  # two type parameters

The ASTs for both of those are the same, so it would be difficult for mypy
to distinguish them.

I do agree that it would be nice to write types like ([str], [int]), but
there are some practical problems.
___
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/BZBQFKZFBFE7VQZZ5FEMNYN3KJDZPNMF/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Implementing string unary operators

2021-10-12 Thread Jelle Zijlstra
El mar, 12 oct 2021 a las 16:51, Jeremiah Vivian (<
nohackingofkrow...@gmail.com>) escribió:

> I posted a previous thread about overloading the unary `+` operator in
> strings with `ord`, and that expanded to more than just the unary `+`
> operator. So I'm saying now, there should be these implementations:
> > +string - `int(string, 10)` (or just `int(string)`)
> > -string - `int(string, 8)`
> > ~string - `int(string, 16)`
>
> Or:
> > +string - `string.lstrip()`
> > -string - `string.rstrip()`
> > ~string - `string.strip()`
>
> If anyone has better ideas, they can post it here.
>
Your other post mostly attracted sarcastic replies, so I'll be more direct:
It's highly unlikely that this will go anywhere.

To get a new operator on a builtin type, you'll have to show that:
- It's a common operation;
- There's no convenient way to do it already; and
- The meaning of the operator is reasonably clear to a reader of the code.

Recent examples of new features that met that bar are dict | in
https://www.python.org/dev/peps/pep-0584 and matrix multiply in
https://www.python.org/dev/peps/pep-0465/.

I don't think any of these proposals come close to meeting those criteria.


> ___
> 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/E2NCFN5ASRHTP7HYWXL5DXDZ7LCTHA2G/
> 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/KGAZXAOHVNPAIJQOF6FOI4P6MAPZMZM6/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: More natural type hints for built-in containers

2021-07-28 Thread Jelle Zijlstra
I suggested this before in some typing meetup, but there are a few problems
with it. One is that annotating arguments as "list" or "dict" is often the
wrong thing to do: instead, people should use broader, immutable types like
Iterable, Sequence, or Mapping, to avoid variance problems (
https://mypy.readthedocs.io/en/stable/common_issues.html#invariance-vs-covariance
).

El mar, 27 jul 2021 a las 20:13, Ignacio Pickering ()
escribió:

> Currently type hints for built-in containers are, in my opinion, less
> succint than required. I suspect it is probably not very difficult for a
> type checker to interpret something like this for example:
>
> var1: {str: (int, int)} = {"label": (1, 2)}
> var2: {str} = {"other_label"}
>
> def function(param1: {int: str} = {1: "foo"}, param2: (int, ...) = (1, 2,
> 3)) -> (int, (str, ...)):
> return 3, ("foo", "bar")
>
> as equivalent to:
>
> var1: dict[str, tuple[int, int]] = {"label": (1, 2)}
> var2: set[str] = {"other_label"}
>
> def function(param1: dict[int, str] = (1, "foo"), param2: tuple[int, ...]
> = (1, 2, 3)) -> tuple[int, tuple[str, ...]]:
> return 3, ("foo", "bar")
>
> I thought of posting something like this as a mypy feature suggestion, but
> I suspect the language would need to modify the way type annotations are
> interpreted for something like it to work (or maybe not?).
> Basically, inside a type annotation, the objects created by (a, b), [a],
> {a: b}, {a} would be reinterpreted as the same thing as constructing
> tuple[a, b], dict[a, b], list[a], set[a].
> I have found myself wanting to write things like this a couple of times,
> so I think this overloaded usage of builtin containters is natural.
> I actually feel it is so natural it must either have been proposed before
> (in which case I would love to give the feature my +1) or there is some
> more or less obvious flaw.
> ___
> 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/SUYRV7DTKSNNFLXLR74GWNQ632WTBCDL/
> 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/YV5MTOPQ5XBDH7LDYBKAWCXMOHKYPKK4/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Deprecate sum of lists

2021-06-17 Thread Jelle Zijlstra
El jue, 17 jun 2021 a las 15:26, Steven D'Aprano ()
escribió:

> On Thu, Jun 17, 2021 at 02:51:44PM -0700, Jelle Zijlstra wrote:
> > El jue, 17 jun 2021 a las 14:45, David Mertz ()
> escribió:
> >
> > > On Thu, Jun 17, 2021, 5:24 PM Ben Rudiak-Gould
> > >
> > >> Okay, slightly off-topic, but can we *please* allow
> > >>
> > >> [*chunk for chunk in list_of_lists]
>
> > My reading is that it would behave like `[*chunk1, *chunk2, *chunk3]`
> would
> > behave if `list_of_lists = [chunk1, chunk2, chunk3]`. I would support
> > adding this behavior to Python.
>
> Oh, that's clever, and I might even have thought of that myself if it
> wasn't described as "off-topic" *wry smile*
>
> So in a generator comprehension, what would it do?
>
> (*chunk for chunk in values)
> # equivalent to... ?
> # (item for chunk in values for item in chunk) perhaps?
>
> I guess we could allow an equivalent in dict comprehensions:
>
> {**chunk for chunk in values}
>
> for unpacking nested dicts or (key,value) pairs.
>
> To me those all feel like the obvious interpretations. And I'm Dutch, so
by the Zen of Python that means it's the right interpretation :)


> Clever... or maybe *too* clever?
>

> --
> Steve
> ___
> Python-ideas mailing list -- python-ideas@python.org
> To unsubscribe send an email to python-ideas-le...@python.org
> https://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at
> https://mail.python.org/archives/list/python-ideas@python.org/message/RL54S6ZAPHBNC5CDYUOJRSWEGSLCBOKS/
> 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/RYTCIEI6P7XTBUJXRGCBVD6JNRU6XP7P/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Deprecate sum of lists

2021-06-17 Thread Jelle Zijlstra
El jue, 17 jun 2021 a las 14:45, David Mertz () escribió:

> On Thu, Jun 17, 2021, 5:24 PM Ben Rudiak-Gould
>
>> Okay, slightly off-topic, but can we *please* allow
>>
>> [*chunk for chunk in list_of_lists]
>>
>
> It is completely non-obvious to me what that would even MEAN. I cannot
> derive anything obvious from other uses of *.
>
> If I had to guess, I'd think that this was tuple unpacking, and the result
> would be a list of tuples. However, apparently in your mind there is some
> way to read this as "flatten." I don't know how to get there mentally
> (other than just memorizing a weird behavior).
>
My reading is that it would behave like `[*chunk1, *chunk2, *chunk3]` would
behave if `list_of_lists = [chunk1, chunk2, chunk3]`. I would support
adding this behavior to 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/M6WRDGFDIEYISMFSWIZL4P4ZTTDKARI5/
> 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/2SJ36GMFAL7IPONSD7J4NZH7LAVIYOFM/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: Define functions without parentheses (if no parameters given)

2021-06-11 Thread Jelle Zijlstra
El jue, 10 jun 2021 a las 19:30, Cameron Simpson () escribió:

> On 11Jun2021 10:01, Cameron Simpson  wrote:
> >So your idea does not suck. But it may not motivate anyone to implement
> >it, or even to agreed that it should be implemented.
>
> It also struck me: functions with _no_ parameters are pretty rare.
>
> I had a glance through my own code and aside from some closures
> (functions within a running function, getting their variables from the
> enclosing scope) I've got a few which either access state from some
> global or which generate something standalone, eg a primes() function
> which just generates the primes starting from 2, a function I maybe even
> don't use. They are very few.
>
I got curious so I checked a large codebase I have access to. Out of 85540
functions, 8244 take no arguments. Many of them are test functions.


>
> So these seem pretty rare. Just how often do you write such a function
> yourself? Got a real world example?
>
> I'm making an argument that this is already a pretty niche situation
> here.
>
> Cheers,
> Cameron Simpson 
> ___
> 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/UXDUUDLJT4JASMBOM7TJXL36MGD3BYI2/
> 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/OX73FEXG5LOGGMBWBIEVU443P55Y3VBA/
Code of Conduct: http://python.org/psf/codeofconduct/


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

2021-06-02 Thread Jelle Zijlstra
El mié, 2 jun 2021 a las 8:34, Alexis Masson ()
escribió:

> 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.
>
> What concretely is the difference you're concerned about? `_` in patterns
doesn't actually bind the name, so you can still use it in the shell for
the last evaluated expression.
___
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/WQO5APLMQ6KHC2RXQ7L67LX6ZBJZQEFM/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: The name Ellipsis should be a constant

2021-05-31 Thread Jelle Zijlstra
El lun, 31 may 2021 a las 12:40, David Mertz () escribió:

> I think making 'Ellipsis' a reserved word is too much.  The analogy with
> non-reserved words like `int`, `str`, `map`, `print`, and so on, illustrate
> this, I think.  I.e. redefining those is likely to cause bad things to
> happen, but we're consenting adults, and in the end they are just names.
>
> However, I think improving the repr() of the Ellipsis object itself to
> remind users of the connection with its special literal `...` is a great
> idea.
>
>
> Why isn't `repr(...)` just `...`?
___
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/GONLS3TPYQWX5E2CW3D563B4CDLMXBQR/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: dataclasses: position-only and keyword-only fields

2021-03-13 Thread Jelle Zijlstra
Another option is something like this (building on Ricky Teachey's
suggestion):

from dataclasses import ArgumentMarker, dataclass

@dataclass
class C:
a: Any  # positional-only
__pos__: ArgumentMarker
b: Any  # normal
__kw_only__: ArgumentMarker
c: Any  # keyword-only

The dataclass machinery would look at the double-underscored names to
figure out when to change argument kind. The annotation ("ArgumentMarker")
doesn't matter, but we need to put *something* there, so why not a new
marker object that clarifies the purpose of the line?

El sáb, 13 mar 2021 a las 7:17, Eric V. Smith ()
escribió:

> On 3/13/2021 9:33 AM, Ricky Teachey wrote:
>
> Fwiw I read Eric's entire proposal (I like it) but totally missed the
> presence of single, double, triple underscores.
>
> Which caused me to be very confused reading Matt De Valle's reply, until I
> went back and noticed them, and the lightbulb went on.
>
> Based on that experience, and also Matt's comment about how people might
> automatically try to add a second signature directive using the same
> variable name, I would suggest that maybe it would be preferred, when
> giving examples in documentation etc, to not use underscores like this as
> the placeholders It is easy to miss that the variable names are
> required to be different.
>
> Hmm. I just noticed that you can specify a class variable multiple times,
> without an error. Subsequent ones overwrite the prior ones in
> __attributes__. That's not good for my proposal, since if you use "_:
> dataclasses.KW_ONLY" followed by "_: dataclasses.POS_ONLY", the second one
> overwrites the first and you lose where the second one was:
> >>> class A:
> ...   a: int
> ...   b: int
> ...   a: float
> ...   c: int
> ...   a: list
> ...
> >>> A.__annotations__
> {'a': , 'b': , 'c': }
>
> For some reason I thought this would raise an error.
>
> This might be a showstopper for this proposal. I'm aware you could do
> something with metaclasses, but one core dataclasses principle is to not
> use metaclasses so that the user is free to use any metaclass for their own
> purposes, without conflict. And I think changing at this point in the game,
> just for this feature, won't fly.
>
> I'll give it some more thought, but I'm not optimistic. I could still add
> kw_only arguments to @dataclass() and field(), but I think the best part of
> the proposal was saying "the rest of the fields are keyword-only".
>
> Or, maybe we could just document this? As I said, I don't think specifying
> multiple KW_ONLY or POS_ONLY (or any combination) would be common. But it's
> an unfortunate trap waiting for the unexpecting user.
>
> Eric
>
>
> Different comment: in the other thread I liked the idea of mimicking the
> syntactical way of writing a function signature (although this might cause
> other problems):
>
> @dataclass
> class C:
> # positional only arguments required at top
> a: Any
> Pos : '/'  # normal only after this line, can't go back
> b: Any
> Kwd: '*'  # kwd only after this line, can't go back
> c: Any
>
> But as Eric pointed out, there could be a lot of value in being able to go
> back and forth. I know think his idea is better.
>
> BIKE SHED:
>
> If switching back and forth does win out, I think we should NOT try to use
> the characters '/' and '*' to specify the signature directives because they
> would lead the reader to believe they work the same as in a function
> signature.
>
> Aside from the issue if going back and forth, in Eric's proposal the
> positional directive comes *before* the positional arguments, rather than
> after like in a function signature. Since this is so different, please
> don't try to use '/'.
>
> ___
> Python-ideas mailing list -- python-ideas@python.org
> To unsubscribe send an email to 
> python-ideas-leave@python.orghttps://mail.python.org/mailman3/lists/python-ideas.python.org/
> Message archived at 
> https://mail.python.org/archives/list/python-ideas@python.org/message/FYDLY5CY7XTJ6TME3RCDHL53VX4AQ3WB/
> Code of Conduct: http://python.org/psf/codeofconduct/
>
> --
> Eric V. Smith
>
> ___
> 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/EOQNTVDRQK5YMR6IV2YVXI3BVSSTVXIP/
> 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/XTOTSDQLQIA3JGZR3TK5ONBQQ74UC2WL/
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Re: add !p to pprint.pformat() in str.format() an f-strings

2020-07-24 Thread Jelle Zijlstra
El mar., 21 jul. 2020 a las 17:27, Guido van Rossum ()
escribió:

> A philosophical problem with this is proposal is that it takes a notation
> that is processed by the bytecode compiler and makes it dependent on user
> code to be imported from the stdlib. We only do that in rare cases — IIRC
> the only other case is ‘import’ calling ‘__import__()’.
>
> There's also `__build_class__`, which gets called during class creation.
___
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/ZYXD5PWFMPIDP5BOFOD2OYCZY6GRAC7A/
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] Backward-incompatible changes for Python 4

2019-04-01 Thread Jelle Zijlstra
El lun., 1 abr. 2019 a las 7:28, Antoine Pietri ()
escribió:

> While the switch to Python 3 did an excellent job in removing some of
> the old inconsistencies we had in the language, pretty much everyone
> agrees that some other backwards-incompatible changes could be made to
> remove some old warts and bring even more consistency to Python.
>
> Since Python 4 is getting closer and closer, I think it’s time to
> finally discuss some of the most obvious changes we should do for
> Python 4. Here is the list I compiled:
>
> - The / operator returns floats, which loses information when both of
> the operands are integer. In Python 4, “1 / 2” should return a
> decimal.Decimal. To ease the transition, we propose to add a new “from
> __future__ import decimal_division” in Python 3.9 to enable this
> behavior.
>
More broadly, one of the best changes in Python 3 was the sanitization of
the string/unicode logic: in Python 2 str and unicode were
mostly-but-not-always interchangeable, but not always, and that led to a
lot of hard to debug errors. Python 3 fixed this by separating the two more
cleanly. Python 4 has the opportunity to do something similar to separate
out another pair of easily confused types: int and float.

Broadly speaking, we should use float for human-understandable numbers, and
int for things that map directly to memory offsets in the computer, and we
should avoid mixing them. This suggests the following changes:
- int + float (and generally any mixed operation between ints and floats)
should throw a TypeError
- len() should return a float
- list.__getitem__ should only accepts ints, not floats
- integer overflow should use two's complement wraparound instead of
infinite precision


> - As most of the Python ecosystem is moving towards async, some of the
> old I/O-blocking APIs should be progressively migrated to an async by
> default model. The most obvious candidate to start this transition is
> the print function, which blocks on the I/O of flushes. We propose to
> make “print” an async coroutine. In Python 3.9, this feature could be
> optionally enabled with “from __future__ import print_coroutine”.
> - To ease compatibility with the Windows API, the PyUnicode* objects
> should be internally represented as an array of uint16_t, as it would
> avoid the conversion overhead from UCS. CPython migration details are
> left as an exercise for the developer.
>
> We think more changes are obviously warranted (e.g adding a new string
> formatting module, changing the semantic of the import system, using
> := in with statements...), but these changes will need specific
> threads of their own.
>
> So, can you think of other backward-incompatible changes that should
> be done in Python 4? Don't hesitate to add your own ideas :-)
>
> Thanks,
>
> --
> Antoine Pietri
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] function annotation enhancement

2019-03-19 Thread Jelle Zijlstra
Your proposed syntax is hard to implement, because it would require
invasive syntax changes to the language itself. That's probably not worth
it.

However, there are other ways to achieve what you're looking for that don't
require changing the language itself. This issue has some proposals:
https://github.com/python/mypy/issues/1641.

El mar., 19 mar. 2019 a las 14:25, Tim Mitchell (<
tim.mitchell.c...@gmail.com>) escribió:

> I would like to propose an enhancement to function annotations.  Here is
> the motivating use case:
> When using callbacks I would like to declare the signature once as a type
> alias and use it to type hint both the function accepting the callback and
> the callbacks themselves.
>
> Currently I can declare the function signare
>
> CallbackType = Callable[[int, str], Any]
>
> and use it for the function/method accepting the callback
>
> def my_func(callabck: CallbackType):
>pass
>
> however it does not work for the callback itself, I have to repeat myself
>
> def my_callback(a: int, b: str) -> None:
> pass
>
> and if I change the signature in CallbackType the typechecker has to know
> that my_callback will be passed to my_func in order to detect the error.
>
> I propose to add a new syntax that declares the type of the function after
> the function name.
>
> def my_callback: CallbackType(a, b):
> pass
>
> any further parameter annotations would be disallowed:
>
> def my_callback: CallbackType(a: int, b: str):   # Syntax error -
> duplicate annotations
> pass
>
>
> If the function parameters do not match the type signare, type hinters
> would flag this as a type mismatch.
>
> def my_callback: CallbackType(a):  # type mismatch
> pass
>
>
> My original thought was that if CallbackType was not a Callable this would
> also be a type error.
> However I have since realized this could be used for declaring the return
> type of properties:
> For example
>
> class MyClass(object):
> @property
> def my_prop: int(self)
> return 10
>
> c = MyClass()
> Then c.my_prop would be type hinted as an integer.
>
> What do people think?
> Cheers
> Tim
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] anyone need a frozenset or bytearray literal?

2018-07-11 Thread Jelle Zijlstra
2018-07-11 16:25 GMT-07:00 Gregory P. Smith :

> Completely obvious what it does, but it irritates my aesthetic
> sensibilities every time I see:
>   frozenset({spam, eggs})
>
> Why? Because I assume under the hood that creates a set of spam and eggs
> before calling frozenset to copy it into a new frozenset object before the
> original set is garbage collected.  Wasteful.  This is in fact what happens
> in CPython 3.7 today.
>
> I'd love to avoid this.  I have no rational measured reason to believe it
> even matters (thus seeding this on python-ideas and not elsewhere), even
> though it would technically speed up frozenset creation.
>
> (a) detecting frozenset({}) as syntax to encode a frozenset in the python
> bytecode would be somewhat magical.  it could break the person unfortunate
> enough to monkeypatch out the frozenset builtin (really? don't do that!).
>
> (b) abusing the concept of letter prefixes as we already have for strings
> on {} syntax would be possible but not at all obvious to a reader:
>
>   f{} or c{} or r{} perhaps.  but then someone would want a frozendict.
>
> (c) adding a .freeze() method to sets which would raise an exception if
> the set's refcount were > 1 and would mutate the type of the set object
> into a frozenset object in place.  refcount assertions are bad, not all VMs
> need refcounts.  The concept of a method that can mutate the type of the
> underlying object in place is... unpythonic.  even though technically
> possible to implement within CPython.
>
> This could be done safely and without too much craziness if .freeze() on a
set returned a new frozenset. The compiler could then safely optimize {a,
set, literal}.freeze() into a frozenset literal, because methods on builtin
types cannot be monkeypatched. There's been talk of a similar optimization
on calls to .format() on string literals (not sure whether it's been
implemented).

Whether implementing that is a good use of anyone's time is a different
question.


> I'm -1 on all of my ideas above.  But figured I'd toss them out there as
> food for thought for the concept.
>
> We lived for years without even having a set literal in the first place.
> So this isn't a big deal.
>
> frozenset is not the only base type that lacks a literals leading to
> loading values into these types involving creation of an intermediate
> throwaway object: bytearray.  bytearray(b'short lived bytes object')
>
> I was going to suggest complex was in this boat as well, but upon
> investigation we appear to do constant folding (or amazing parsingon that
> so 0.3+0.6j does turn into a single LOAD_CONST instead of two consts and an
> addition.  Nice!  Not that I expect practical code to use complex numbers.
>
> -gps
>
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
>
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] Fwd: Replacing Infinite while Loops with an Iterator: async edition

2018-06-24 Thread Jelle Zijlstra
2018-06-24 12:30 GMT-07:00 :

> On Jun 23, 2018, at 21:11, Nathaniel Smith  wrote:
>
>> He's asking for an async version of the 'iter' builtin, presumably
>> something like:
>> async def aiter(async_callable, sentinel):
>>while True:
>>value = await async_callable()
>>if value == sentinel:
>>break
>>yield value
>> -n
>
>
> Yes, exactly (thanks, Nathaniel). Wouldn't that be a useful built-in?
>
> (Greg, I too would be surprised if this were the first time this idea has
> been raised, but I looked before posting and couldn’t immediately
> find prior discussion.)
>
> There is an open issue for this: https://bugs.python.org/issue31861. It
proposes adding aiter() and anext() as builtins.


> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
>
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] Operator for inserting an element into a list

2018-06-17 Thread Jelle Zijlstra
2018-06-17 13:09 GMT-07:00 Chris Angelico :

>
> kwargs.pop("some_key") could plausibly be spelled del
> kwargs["some_key"] if del were (like yield) upgraded to expression.
> Whether that is an improvement or not, I don't know, but at least it's
> logical.
>
That already works. It calls the __delitem__ magic method.


>
> ChrisA
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] A "within" keyword

2018-06-08 Thread Jelle Zijlstra
2018-06-08 20:27 GMT-07:00 Alex Walters :

> Why not...
>
> cool_namespace = SomeNamespaceContextManager()
>
> with cool_namespace:
> def foo():
> pass
>
> advantage being it introduces no new keyword.  The 'disadvantage' is it
> would change semantics of the with statement (as would be required to get
> the names defined in the suite of the context manager)
>
> Actually, this is probably doable now. You can get the globals of the
calling code by doing sys._getframe(), then check which names are added
while the context manager is active.

>
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


[Python-ideas] Fwd: Pattern Matching Syntax

2018-05-11 Thread Jelle Zijlstra
2018-05-11 22:01 GMT-04:00 Robert Roskam :

> Hey Steven,
>
> I'm also at PyCon. Shall we take this off list and attempt to meet up and
> discuss?
>
> I'm also at PyCon and interested in meeting about this. I just wrote up a
basic and incomplete implementation for pattern-matching yesterday between
and after: talks: https://github.com/JelleZijlstra/cpython/blob/
matchcase/Lib/test/test_matching.py. It's nowhere near complete, but an
implementation like this can help inform what the syntax should look like.
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] PEP 572 version 2: Statement-Local Name Bindings

2018-03-02 Thread Jelle Zijlstra
2018-03-02 7:03 GMT-08:00 Robert Vanden Eynde :

> +1 on extracting the big win for "if" and "while" (the regex case is
> wonderul). It would be see as an "extended if/while" rather than a general
> statement assignation.
>
>
I wonder if we could have a more limited change to the language that would
allow only the as/while use cases. Specifically, that means we could do:

while do_something() as x:
print(x)

if re.match(r'.*', text) as match:
print(match.groups())

Parentheses would no longer be necessary for syntactic ambiguity, and there
is no real need for new scoping rules—we could just create new locals.

This would alleviate some of the problems with the current proposal, such
as complicated scoping rules and ugly syntax in comprehensions.


> +1 on list comprehensions, even if I prefer the
> [(y, x/y) with y = f(x) for x in range(5)] or [(y, x/y) for x in range(5)
> with y = f(x)] syntax (more close to "for y in [ f(x) ]".
>
> Le 2 mars 2018 15:54, "Rhodri James"  a écrit :
>
> On 02/03/18 11:43, Chris Angelico wrote:
>
>> After dozens of posts and a wide variety of useful opinions and
>> concerns being raised, here is the newest version of PEP 572 for your
>> debating pleasure.
>>
>
> I haven't said this yet, so thanks Chris for putting this all together.
> Even if the result is a rejected PEP, at least we have everything in one
> place.
>
> [snip]
>
>
>  # Compound statements usually enclose everything...
>>  if (re.match(...) as m):
>>  print(m.groups(0))
>>  print(m) # NameError
>>
>
> This (and the equivalent in while loops) is the big win in the PEP, in my
> opinion.  The number of ugly loops I've had to write in Python because I
> can't write "while (something_to_do() as event):"...  +1 on this.
>
>
>  # Using a statement-local name
>>  stuff = [[(f(x) as y), x/y] for x in range(5)]
>>
>
> As Paul said, the asymmetry of this bothers me a lot.  It doesn't read
> naturally to me. -1 on this.
>
>
> 1. What happens if the name has already been used? ``(x, (1 as x), x)``
>> Currently, prior usage functions as if the named expression did not
>> exist (following the usual lookup rules); the new name binding will
>> shadow the other name from the point where it is evaluated until the
>> end of the statement.  Is this acceptable?  Should it raise a syntax
>> error or warning?
>>
>
> I wouldn't worry too much about this case.  Anyone gratuitously reusing
> names like that deserves all that will be coming to them.
>
> Alternative proposals
>> =
>>
>> 3. ``with... as``::
>>
>> stuff = [(y, x/y) with f(x) as y for x in range(5)]
>>
>> As per option 2, but using ``as`` in place of the equals sign. Aligns
>> syntactically with other uses of ``as`` for name binding, but a simple
>> transformation to for-loop longhand would create drastically different
>> semantics; the meaning of ``with`` inside a comprehension would be
>> completely different from the meaning as a stand-alone statement.
>>
>
> Honestly I prefer this syntax for comprehensions.  It doesn't read
> perfectly but it's good enough (though I am a mathematician by original
> training, so set notation works for me anyway), and the syntax is clear and
> limited.
>
> I'm not sure the case for fully general statement-local variables has been
> made.
>
> So, counter-proposal(s):
>
> 1. Allow "(f() as a)" in the conditions of "if" and "while" statements,
> after some arguing as to whether "a" is a special snowflake or just a
> normal local variable.
>
> 2. Add a "with" clause to comprehensions to make comprehension-local
> variables (presumably the same class of thing as the iteration variables).
>
> --
> Rhodri James *-* Kynesim Ltd
>
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
>
>
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
>
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] Ternary operators in list comprehensions

2017-10-05 Thread Jelle Zijlstra
[x if x & 1 else 'even' for x in a]

An `if` at the end of the comprehension means a condition on whether to
include the value.

Also, this question would have been better asked on python-list.

2017-10-05 8:40 GMT-07:00 Jason H :

> >>> a = [1,2,3]
> >>> [ x for x  in a if x & 1]
> [1, 3]
> >>> [ x for x  in a if x & 1 else 'even']
>   File "", line 1
> [ x for x  in a if x & 1 else 'even']
> ^
> SyntaxError: invalid syntax
>
> I expected [1, 'even', 3]
>
> I would expect that the if expression would be able to provide alternative
> values through else.
>
> The work around blows it out to:
> l = []
> for x in a:
>   if x&1:
> l.append(x)
>   else:
> l.append('even')
>
>
> Unless there is a better way?
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] PEP 563 and expensive backwards compatibility

2017-09-13 Thread Jelle Zijlstra
2017-09-13 13:01 GMT-07:00 Jim J. Jewett :

> On Wed, Sep 13, 2017 at 3:12 PM, Lukasz Langa  wrote:
> > On Sep 13, 2017, at 2:56 PM, Jim J. Jewett  wrote:
>
> >> I am generally supportive of leaving the type annotations
> >> unprocessed by default, but there are use cases where
> >> they should be processed (and even cases where doing it
> >> at the right time matters, because of a side effect).
>
> > What is the "right time" you're speaking of?
>
> The "right time" is whenever they are currently evaluated.
> (Definition time, I think, but won't swear.)
>
> For example, the "annotation" might really be a call to a logger,
> showing the current environment, including names that will be rebound
> before the module finishes loading.
>
> I'm perfectly willing to agree that even needing this much control
> over timing is a code smell, but it is currently possible, and I would
> rather it not become impossible.
>

Is this just a theoretical concern? Unless there is significant real-world
code doing this sort of thing, I don't see much of a problem in deprecating
such code using the normal __future__-based deprecation cycle.


>
> At a minimum, it seems like "just run this typing function that you
> should already be using" should either save the right context, or the
> PEP should state explicitly that this functionality is being
> withdrawn.  (And go ahead and suggest a workaround, such as running
> the code before the method definition, or as a decorator.)
>
>
> >> (1)  The PEP suggests opting out with @typing.no_type_hints ...
>
> > This is already possible. PEP 484 specifies that
>
> > "A # type: ignore comment on a line by itself is equivalent to adding an
> > inline # type: ignore to each line until the end of the current indented
> > block. At top indentation level this has effect of disabling type
> checking
> > until the end of file."
>
> Great!  Please mention this as well as (or perhaps instead of)
> typing.no_type_check.
>
>
> >> It would be a bit messy (like the old coding cookie),
> >> but recognizing a module-wide
>
> >> # typing.no_type_hints
>
> >> comment and then falling back to the current behavior
> >> would be enough for me.
>
> > Do you know of any other per-module feature toggle of this kind?
>
> No, thus the comment about it being messy.  But it does offer one way
> to ensure that annotations are evaluated within the proper
> environment, even without having to save those environments.
>
> -jJ
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] PEP 561: Distributing and Packaging Type Information

2017-09-10 Thread Jelle Zijlstra
2017-09-10 18:10 GMT-07:00 Ethan Smith <et...@ethanhs.me>:

>
>
> On Sun, Sep 10, 2017 at 5:39 PM, Jelle Zijlstra <jelle.zijls...@gmail.com>
> wrote:
>
>> Congratulations on your first PEP! This is solving an important problem
>> for typing in Python, so I'm glad we're tackling it.
>>
>
> Thanks!
>
>>
>> 
>>>
>>> Furthermore, package authors are wishing to distribute code that has
>>> inline type information, and there currently is no standard method to
>>> distribute packages with inline type annotations or syntax that can
>>> simultaneously be used at runtime and in type checking.
>>>
>>> This feels like it should be the first paragraph: it describes the
>> important problem we're solving, and the first paragraph is just details on
>> why the previous solutions don't work. Perhaps you could talk more about
>> how people are running into problems because of the absence of a way to
>> distribute typed packages. For example, if you're working on a proprietary
>> codebase, it's likely that you're relying on other internal packages, but
>> there is no good way to do that right now (short of setting MYPYPATH). For
>> open source package, you can add them to typeshed, but that adds overhead
>> for the package maintainer and ties you to mypy's release cycle.
>>
>
> Inline types are one of the problems this PEP tries to resolve. But it
> also tries to solve the issue of distributing stubs. You are correct that
> typeshed should be mentioned as a current method. And I will re-word this
> the next change I make.
>
>> Specification
>>> =
>>>
>>> There are several motivations and methods of supporting typing in a 
>>> package. This PEP 
>>> recognizes three (3) types of packages that may be created:
>>>
>>> 1. The package maintainer would like to add type information inline.
>>>
>>> 2. The package maintainer would like to add type information via stubs.
>>>
>>> 3. A third party would like to share stub files for a package, but the
>>>maintainer does not want to include them in the source of the package.
>>>
>>>
>>> Where does the typeshed repo fit in here? Does the PEP propose to
>> deprecate using typeshed for third-party packages, or should typeshed
>> continue to be the repository for major third-party packages? Either way,
>> it should be discussed.
>>
>
> Yes, I agree I should mention typeshed. I believe the best approach would
> be to encourage new third-party packages to use this PEP's approach to stub
> packages, keep typeshed as is, and migrate the third party part of typeshed
> into packages if maintainers are found.
>
>> This PEP aims to support these scenarios and make them simple to add to
>>> packaging and deployment.
>>>
>>> The two major parts of this specification are the packaging specifications
>>> and the resolution order for resolving module type information. This spec
>>> is meant to replace the ``shared/typehints/pythonX.Y/`` spec of PEP 484 
>>> [1]_.
>>>
>>> Packaging Type Information
>>> --
>>>
>>> Packages must opt into supporting typing. This will be done though a 
>>> distutils
>>> extension [2]_, providing a ``typed`` keyword argument to the distutils
>>> ``setup()`` command. The argument value will depend on the kind of type
>>> information the package provides. The distutils extension will be added to 
>>> the
>>> ``typing`` package. Therefore a package maintainer may write
>>>
>>> Is the addition to the `typing` package just a legacy feature for Python
>> versions without typing in the standard library? This should be made
>> explicit.
>>
>
> The intent here is that the typing package would be required for the extra
> setup keyword to work, otherwise it would fail.
>
Then I would have to install the `typing` PyPI package even if I am only
using Python 3.7+? That seems suboptimal. Perhaps the new keyword can be
part of Python core in 3.7 and added to `typing_extensions` for 3.5 and 3.6.

> ::
>>>
>>> setup(
>>> ...
>>> setup_requires=["typing"],
>>> typed="inline",
>>> ...
>>> )
>>>
>>> Inline Typed Packages
>>> '
>>>
>>> Packages that have inline type annotations simply have to pass the value
>>> ``"inline

Re: [Python-ideas] PEP 561: Distributing and Packaging Type Information

2017-09-10 Thread Jelle Zijlstra
Congratulations on your first PEP! This is solving an important problem for
typing in Python, so I'm glad we're tackling it.

2017-09-10 16:05 GMT-07:00 Ethan Smith :

> Hello,
>
> I have just published my first PEP, on packaging type information. I would
> appreciate comments and suggestions. The PEP can be found at
> https://www.python.org/dev/peps/pep-0561/
>
> I have also duplicated the text below.
>
> Thanks!
>
> --
>
>
> PEP: 561
> Title: Distributing and Packaging Type Information
> Author: Ethan Smith 
> Status: Draft
> Type: Standards Track
> Content-Type: text/x-rst
> Created: 09-Sep-2017
> Python-Version: 3.7
> Post-History:
>
>
> Abstract
> 
>
> PEP 484 introduced type hints to Python, with goals of making typing
> gradual and easy to adopt. Currently, typing information must be distributed
> manually. This PEP provides a standardized means to package and distribute
> type information and an ordering for type checkers to resolve modules and
> collect this information for type checking using existing packaging
> architecture.
>
>
> Rationale
> =
>
> PEP 484 has a brief section on distributing typing information. In this
> section [1]_ the PEP recommends using ``shared/typehints/pythonX.Y/`` for
> shipping stub files. However, manually adding a path to stub files for each
> third party library does not scale. The simplest approach people have taken
> is to add ``site-packages`` to their ``PYTHONPATH``, but this causes type
> checkers to fail on packages that are highly dynamic (e.g. sqlalchemy
> and Django).
>
> Furthermore, package authors are wishing to distribute code that has
> inline type information, and there currently is no standard method to
> distribute packages with inline type annotations or syntax that can
> simultaneously be used at runtime and in type checking.
>
> This feels like it should be the first paragraph: it describes the
important problem we're solving, and the first paragraph is just details on
why the previous solutions don't work. Perhaps you could talk more about
how people are running into problems because of the absence of a way to
distribute typed packages. For example, if you're working on a proprietary
codebase, it's likely that you're relying on other internal packages, but
there is no good way to do that right now (short of setting MYPYPATH). For
open source package, you can add them to typeshed, but that adds overhead
for the package maintainer and ties you to mypy's release cycle.

>
>
> Specification
> =
>
> There are several motivations and methods of supporting typing in a package.  
>This PEP recognizes three (3) 
> types of packages that may be created:
>
> 1. The package maintainer would like to add type information inline.
>
> 2. The package maintainer would like to add type information via stubs.
>
> 3. A third party would like to share stub files for a package, but the
>maintainer does not want to include them in the source of the package.
>
>
> Where does the typeshed repo fit in here? Does the PEP propose to
deprecate using typeshed for third-party packages, or should typeshed
continue to be the repository for major third-party packages? Either way,
it should be discussed.

> This PEP aims to support these scenarios and make them simple to add to
> packaging and deployment.
>
> The two major parts of this specification are the packaging specifications
> and the resolution order for resolving module type information. This spec
> is meant to replace the ``shared/typehints/pythonX.Y/`` spec of PEP 484 [1]_.
>
> Packaging Type Information
> --
>
> Packages must opt into supporting typing. This will be done though a distutils
> extension [2]_, providing a ``typed`` keyword argument to the distutils
> ``setup()`` command. The argument value will depend on the kind of type
> information the package provides. The distutils extension will be added to the
> ``typing`` package. Therefore a package maintainer may write
>
> Is the addition to the `typing` package just a legacy feature for Python
versions without typing in the standard library? This should be made
explicit.

>
> ::
>
> setup(
> ...
> setup_requires=["typing"],
> typed="inline",
> ...
> )
>
> Inline Typed Packages
> '
>
> Packages that have inline type annotations simply have to pass the value
> ``"inline"`` to the ``typed`` argument in ``setup()``.
>
> Stub Only Packages
> ''
>
> For package maintainers wishing to ship stub files containing all of their
> type information, it is prefered that the ``*.pyi`` stubs are alongside the
> corresponding ``*.py`` files. However, the stubs may be put in a sub-folder
> of the Python sources, with the same name the ``*.py`` files are in. For
> example, the ``flyingcircus`` package would 

Re: [Python-ideas] PEP 550 v2

2017-08-16 Thread Jelle Zijlstra
2017-08-16 10:37 GMT+02:00 Nathaniel Smith <n...@pobox.com>:

> On Tue, Aug 15, 2017 at 11:53 PM, Jelle Zijlstra
> <jelle.zijls...@gmail.com> wrote:
> > Minor suggestion: Could we allow something like
> > `sys.set_new_context_item(description='mylib.context',
> > initial_value='spam')`? That would make it easier for type checkers to
> infer
> > the type of a ContextItem, and it would save a line of code in the common
> > case.
>
> This is a really handy feature in general, actually! In fact all of
> asyncio's thread-locals define initial values (using a trick involving
> subclassing threading.local), and I recently added this feature to
> trio.TaskLocal as well just because it's so convenient.
>
> However, something that you realize almost immediately when trying to
> use this is that in many cases, what you actually want is an initial
> value *factory*. Like, if you write new_context_item(initial_value=[])
> then you're going to have a bad time. So, should we support something
> like new_context_item(initializer=lambda: [])?
>
> The semantics are a little bit subtle. I guess it would be something
> like: if ci.get() goes to find the value and fails at all levels, then
> we call the factory function and assign its return value to the
> *deepest* LC, EC[0]. The idea being that we're pretending that the
> value was there all along in the outermost scope, you just didn't
> notice before now.
>
> > With this modification, the type of new_context_item would be
> >
> > @overload
> > def new_context_item(*, description: str, initial_value: T) ->
> > ContextItem[T]: ...
> > @overload
> > def new_context_item(*, description: str) -> ContextItem[Any]: ...
> >
> > If we only allow the second variant, type checkers would need some sort
> of
> > special casing to figure out that after .set(), .get() will return the
> same
> > type.
>
> I'm not super familiar with PEP 484.
>
> Would using a factory function instead of an initial value break this
> type inference?
>
> If you want to automatically infer that whatever type I use to
> initialize the value is the only type it can ever have, is there a way
> for users to easily override that? Like could I write something like
>
> my_ci: ContextItem[int, str] = new_context_item(initial_value=0)
>
> It would be `ContextItem[Union[int, str]]`, but yes, that should work.


> ?
>
> -n
>
> --
> Nathaniel J. Smith -- https://vorpus.org
>
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] PEP 550 v2

2017-08-16 Thread Jelle Zijlstra
2017-08-16 1:55 GMT+02:00 Yury Selivanov :

> Hi,
>
> Here's the PEP 550 version 2.  Thanks to a very active and insightful
> discussion here on Python-ideas, we've discovered a number of
> problems with the first version of the PEP.  This version is a complete
> rewrite (only Abstract, Rationale, and Goals sections were not updated).
>
> The updated PEP is live on python.org:
> https://www.python.org/dev/peps/pep-0550/
>
> There is no reference implementation at this point, but I'm confident
> that this version of the spec will have the same extremely low
> runtime overhead as the first version.  Thanks to the new ContextItem
> design, accessing values in the context is even faster now.
>
> Thank you!
>
>
> PEP: 550
> Title: Execution Context
> Version: $Revision$
> Last-Modified: $Date$
> Author: Yury Selivanov 
> Status: Draft
> Type: Standards Track
> Content-Type: text/x-rst
> Created: 11-Aug-2017
> Python-Version: 3.7
> Post-History: 11-Aug-2017, 15-Aug-2017
>
>
> Abstract
> 
>
> This PEP proposes a new mechanism to manage execution state--the
> logical environment in which a function, a thread, a generator,
> or a coroutine executes in.
>
> A few examples of where having a reliable state storage is required:
>
> * Context managers like decimal contexts, ``numpy.errstate``,
>   and ``warnings.catch_warnings``;
>
> * Storing request-related data such as security tokens and request
>   data in web applications, implementing i18n;
>
> * Profiling, tracing, and logging in complex and large code bases.
>
> The usual solution for storing state is to use a Thread-local Storage
> (TLS), implemented in the standard library as ``threading.local()``.
> Unfortunately, TLS does not work for the purpose of state isolation
> for generators or asynchronous code, because such code executes
> concurrently in a single thread.
>
>
> Rationale
> =
>
> Traditionally, a Thread-local Storage (TLS) is used for storing the
> state.  However, the major flaw of using the TLS is that it works only
> for multi-threaded code.  It is not possible to reliably contain the
> state within a generator or a coroutine.  For example, consider
> the following generator::
>
> def calculate(precision, ...):
> with decimal.localcontext() as ctx:
> # Set the precision for decimal calculations
> # inside this block
> ctx.prec = precision
>
> yield calculate_something()
> yield calculate_something_else()
>
> Decimal context is using a TLS to store the state, and because TLS is
> not aware of generators, the state can leak.  If a user iterates over
> the ``calculate()`` generator with different precisions one by one
> using a ``zip()`` built-in, the above code will not work correctly.
> For example::
>
> g1 = calculate(precision=100)
> g2 = calculate(precision=50)
>
> items = list(zip(g1, g2))
>
> # items[0] will be a tuple of:
> #   first value from g1 calculated with 100 precision,
> #   first value from g2 calculated with 50 precision.
> #
> # items[1] will be a tuple of:
> #   second value from g1 calculated with 50 precision (!!!),
> #   second value from g2 calculated with 50 precision.
>
> An even scarier example would be using decimals to represent money
> in an async/await application: decimal calculations can suddenly
> lose precision in the middle of processing a request.  Currently,
> bugs like this are extremely hard to find and fix.
>
> Another common need for web applications is to have access to the
> current request object, or security context, or, simply, the request
> URL for logging or submitting performance tracing data::
>
> async def handle_http_request(request):
> context.current_http_request = request
>
> await ...
> # Invoke your framework code, render templates,
> # make DB queries, etc, and use the global
> # 'current_http_request' in that code.
>
> # This isn't currently possible to do reliably
> # in asyncio out of the box.
>
> These examples are just a few out of many, where a reliable way to
> store context data is absolutely needed.
>
> The inability to use TLS for asynchronous code has lead to
> proliferation of ad-hoc solutions, which are limited in scope and
> do not support all required use cases.
>
> Current status quo is that any library, including the standard
> library, that uses a TLS, will likely not work as expected in
> asynchronous code or with generators (see [3]_ as an example issue.)
>
> Some languages that have coroutines or generators recommend to
> manually pass a ``context`` object to every function, see [1]_
> describing the pattern for Go.  This approach, however, has limited
> use for Python, where we have a huge ecosystem that was built to work
> with a TLS-like context.  Moreover, passing the context explicitly
> does not work at all for libraries like ``decimal`` 

Re: [Python-ideas] New PEP 550: Execution Context

2017-08-11 Thread Jelle Zijlstra
This is exciting and I'm happy that you're addressing this problem.

We've solved a similar problem in our asynchronous programming framework,
asynq. Our solution (implemented at
https://github.com/quora/asynq/blob/master/asynq/contexts.py) is similar to
that in PEP 521: we enhance the context manager protocol with pause/resume
methods instead of using an enhanced form of thread-local state.

Some of our use cases can't be implemented using this PEP; notably, we use
a timing context that times how long an asynchronous function takes by
repeatedly pausing and resuming the timer. However, this timing context
adds significant overhead because we have to call the pause/resume methods
so often. Overall, your approach is almost certainly more performant.

2017-08-11 15:37 GMT-07:00 Yury Selivanov :

> Hi,
>
> This is a new PEP to implement Execution Contexts in Python.
>
> The PEP is in-flight to python.org, and in the meanwhile can
> be read on GitHub:
>
> https://github.com/python/peps/blob/master/pep-0550.rst
>
> (it contains a few diagrams and charts, so please read it there.)
>
> Thank you!
> Yury
>
>
> PEP: 550
> Title: Execution Context
> Version: $Revision$
> Last-Modified: $Date$
> Author: Yury Selivanov 
> Status: Draft
> Type: Standards Track
> Content-Type: text/x-rst
> Created: 11-Aug-2017
> Python-Version: 3.7
> Post-History: 11-Aug-2017
>
>
> Abstract
> 
>
> This PEP proposes a new mechanism to manage execution state--the
> logical environment in which a function, a thread, a generator,
> or a coroutine executes in.
>
> A few examples of where having a reliable state storage is required:
>
> * Context managers like decimal contexts, ``numpy.errstate``,
>   and ``warnings.catch_warnings``;
>
> * Storing request-related data such as security tokens and request
>   data in web applications;
>
> * Profiling, tracing, and logging in complex and large code bases.
>
> The usual solution for storing state is to use a Thread-local Storage
> (TLS), implemented in the standard library as ``threading.local()``.
> Unfortunately, TLS does not work for isolating state of generators or
> asynchronous code because such code shares a single thread.
>
>
> Rationale
> =
>
> Traditionally a Thread-local Storage (TLS) is used for storing the
> state.  However, the major flaw of using the TLS is that it works only
> for multi-threaded code.  It is not possible to reliably contain the
> state within a generator or a coroutine.  For example, consider
> the following generator::
>
> def calculate(precision, ...):
> with decimal.localcontext() as ctx:
> # Set the precision for decimal calculations
> # inside this block
> ctx.prec = precision
>
> yield calculate_something()
> yield calculate_something_else()
>
> Decimal context is using a TLS to store the state, and because TLS is
> not aware of generators, the state can leak.  The above code will
> not work correctly, if a user iterates over the ``calculate()``
> generator with different precisions in parallel::
>
> g1 = calculate(100)
> g2 = calculate(50)
>
> items = list(zip(g1, g2))
>
> # items[0] will be a tuple of:
> #   first value from g1 calculated with 100 precision,
> #   first value from g2 calculated with 50 precision.
> #
> # items[1] will be a tuple of:
> #   second value from g1 calculated with 50 precision,
> #   second value from g2 calculated with 50 precision.
>
> An even scarier example would be using decimals to represent money
> in an async/await application: decimal calculations can suddenly
> lose precision in the middle of processing a request.  Currently,
> bugs like this are extremely hard to find and fix.
>
> Another common need for web applications is to have access to the
> current request object, or security context, or, simply, the request
> URL for logging or submitting performance tracing data::
>
> async def handle_http_request(request):
> context.current_http_request = request
>
> await ...
> # Invoke your framework code, render templates,
> # make DB queries, etc, and use the global
> # 'current_http_request' in that code.
>
> # This isn't currently possible to do reliably
> # in asyncio out of the box.
>
> These examples are just a few out of many, where a reliable way to
> store context data is absolutely needed.
>
> The inability to use TLS for asynchronous code has lead to
> proliferation of ad-hoc solutions, limited to be supported only by
> code that was explicitly enabled to work with them.
>
> Current status quo is that any library, including the standard
> library, that uses a TLS, will likely not work as expected in
> asynchronous code or with generators (see [3]_ as an example issue.)
>
> Some languages that have coroutines or generators recommend to
> manually pass a ``context`` object to every 

Re: [Python-ideas] Idea : for smarter assignment?

2017-07-21 Thread Jelle Zijlstra
2017-07-21 10:07 GMT-07:00 Jason H :

> I experimented with Python in college and I've been for close to 20 years
> now. (Coming and going as needed) I love the language. But there is one
> annoyance that I continually run into.
>
> There are basically two assignment operators, based on context, = and :
> a = 1
> { a: 1 }
>
> They cannot be used interchangeably:
> a: 1 # error
> {a=1} # error
>
> I don't think I should be this way.
>
> There are times when I have a bunch of variables that I want to collect
> into an object or destructure. This involves adding commas, and swapping
> the :/=. I don't have a good fix for  the adding of commas (maybe a
> newline?)
> but I think : should at least be accepted as = everywhere except in ifs:
> a: 1 # same as a = 1
>
> One area where it might help (although the python parser already catches
> it) is in ifs:
> if a:1 # always error ?
> if a=1 # currently error, but might be accepted shorthand for == ?
>
> Ideally, I could take
> a: 1
> b: 2
>

This conflicts with PEP 526 variable annotations: "a: int" already means "a
is of type int", but with your syntax there would be no way to distinguish
between "a = int" and "a: int".


> then in 3 edits:
> 1. first line prepend 'x: {'
> 2. last line append '}'
> 3. indent between { }
>
> I guess his would imply that { open up an assignment scope, where newlines
> are commas if the last line did not end with an operator or the next line
> did not start with an operator:
> x: {
>   a: x -  # - operator
> f(x)
>   b:  # : operator
> 5487234728394720348988734574357
>   c: 7# c is 13, no trailing operator but next line has a preceding
> operator
> + 6
> }
>
> The only issue then is how do we address a?
> x.a# looks fine to me
> x['a'] # as a dict, but the conversion of a to string 'a' could be
> confusing.
>
>
> Additionally, I was also thinking about : as an implied await:
> a = await f() # await generator
> a: f()# await generator, or direct assignment if return type is
> not a generator/async func
>
> Thoughts? Please be gentle :-)
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] Exploiting type-homogeneity in list.sort() (again!)

2017-03-05 Thread Jelle Zijlstra
2017-03-05 22:08 GMT-08:00 Elliot Gorokhovsky :
> Another solution: check if there is more than one thread; if there is, then
> disable optimization. Is sorting in multithreaded programs common enough to
> warrant adding the complexity to deal with it?
>

I think using a global is unsafe even without multithreading, because
the compare function itself could end up doing list.sort() (it's
calling arbitrary Python code after all).

>
> On Sun, Mar 5, 2017 at 10:52 PM Elliot Gorokhovsky
>  wrote:
>>
>> On Sun, Mar 5, 2017 at 10:45 PM Elliot Gorokhovsky
>>  wrote:
>>>
>>>
>>> the problem is, how can we get a unique identifier for the thread in a
>>> platform-independent way? Any ideas?
>>
>>
>> Oh, I could probably just copy over code from threading.get_ident()... not
>> sure if the key-value table is a good solution, though.
>
>
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/


Re: [Python-ideas] add __contains__ into the "type" object

2017-02-28 Thread Jelle Zijlstra
2017-02-28 15:12 GMT-08:00 Steven D'Aprano :
> On Wed, Mar 01, 2017 at 07:02:23AM +0800, 语言破碎处 wrote:
>>
>> where we use types?
>> almost:
>> isinstance(obj, T);
>> # issubclass(S, T);
>>
>> Note that TYPE is SET;
>
> What does that mean? I don't understand.
>
>
>> if we add __contains__ and __le__ into "type",
>> then things become:
>> obj in T;
>
> But obj is **not** in T, since T is a type, not a container.
>

But in type theory, types are sets in some sense. For example, the
bool type is the set {True, False}, and the int type is the infinite
set {..., -1, 0, 1, ...}. Similarly, typing.py has a Union type:
Union[A, B] is the union of the types A and B. Subclasses are subsets
of their parent classes, because their set of possible values is a
subset of the possible values of their parent class.

The OP seems to be proposing that we reflect this identity between
types and sets in Python by spelling "isinstance(obj, T)" as "obj in
T" and "issubclass(S, T)" as "S <= T". This proposal has some solid
theory behind it and I don't think it would be hard to implement, but
it doesn't seem like a particularly useful change to me. It wouldn't
really enable anything we can't do now, and it may be confusing to
people reading code that "obj in list" does something completely
different from "obj in list()".

> "is-a" tests are not the same as "in" tests. They are completely
> unrelated comparisons.
>
> http://www.w3resource.com/java-tutorial/inheritance-composition-relationship.php
>
> The Wikipedia page on is-a is terribly complicated, but folks may get
> something from it:
>
> https://en.wikipedia.org/wiki/Is-a
>
>
>
> --
> Steve
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Re: [Python-ideas] Python dependancies

2017-01-15 Thread Jelle Zijlstra
2017-01-14 21:24 GMT-08:00 Mathieu TORTUYAUX :

> Hello everyone,
>
> I'm used to work with python and contribute to open-source projects. And
> now, many projects need to run with dependancies. So I wondering, if it
> could be a good idea to integrate a sniffer into Python to detecte if
> project's dependancies are up to date.
>
pip already supports something like this: `pip list --outdated` will print
out installed packages for which a more recent version is available.

> And each time Python project is run developer will be aware if
> dependancies are up to date.
>
>
> I think isn't the first time that this idea is submitted. So I am looking
> forward your feedbacks !
>
> Mathieu Tortuyaux
>
>
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

[Python-ideas] api suggestions for the cProfile module

2017-01-10 Thread Jelle Zijlstra
2017-01-10 8:57 GMT-08:00 Ethan Furman :

> On 01/10/2017 08:36 AM, Thane Brimhall wrote:
>
> Does anyone have thoughts on this topic? I assume the silence is because
>>  this suggestion is too trivial to matter.
>>
>
> Sometimes it's just a matter of timing.  :)
>
> I use cProfile a lot, and would like to suggest three backwards-compatible
>>  improvements to the API.
>>
>> 1: When using cProfile on a specific piece of code I often use the
>>  enable() and disable() methods. It occurred to me that this would
>>  be an obvious place to use a context manager.
>>
>
> Absolutely.
>
> 2: Enhance the `print_stats` method on Profile to accept more options
>>  currently available only through the pstats.Stats class. For example,
>>  strip_dirs could be a boolean argument, and limit could accept an int.
>>  This would reduce the number of cases you'd need to use the more complex
>>  API.
>>
>
> I don't have much experience with cProfile, but this seems reasonable.
>
> 3: I often forget which string keys are available for sorting. It would
>>  be nice to add an enum for these so a user could have their linter and
>>  IDE check that value pre-runtime. Since it would subclass `str` and
>>  `Enum` it would still work with all currently existing code.
>>
>
> Absolutely!  :)
>
> The current documentation contains the following code:
>>
>> import cProfile, pstats, io
>> pr = cProfile.Profile()
>> pr.enable()
>> # ... do something ...
>> pr.disable()
>> s = io.StringIO()
>> sortby = 'cumulative'
>> ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
>> ps.print_stats()
>> print(s.getvalue())
>>
>> While the code below doesn't exactly match the functionality above (eg.
>> not
>>  using StringIO), I envision the context manager working like this, along
>>  with some adjustments on how to get the stats from the profiler:
>>
>> import cProfile, pstats
>> with cProfile.Profile() as pr:
>>  # ... do something ...
>>  pr.print_stats(sort=pstats.Sort.cumulative, limit=10,
>> strip_dirs=True)
>>
>> As you can see, the code is shorter and somewhat more self-documenting.
>> The
>>  best thing about these suggestions is that as far as I can tell they
>> would
>>  be backwards-compatible API additions.
>>
>
> The `pr.print_stats... line should not be inside the `with` block unless
> you want to profile that part as well.
>
> These suggestions seem fairly uncontroversial.  Have you opened an issue
> on the issue tracker?
>
> The fun part of the patch will be the C code, but a Python
> proof-of-concept would be useful.
>
> These changes may not even require C code, since (contrary to its name)
cProfile actually is implemented partly in Python. For example, the context
manager change could be made simply by adding __enter__ and __exit__ to the
cProfile.Profile class.

> --
> ~Ethan~
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Re: [Python-ideas] Add optional defaults to namedtuple

2016-12-01 Thread Jelle Zijlstra
2016-11-30 8:11 GMT-08:00 Guido van Rossum :

> On Wed, Nov 30, 2016 at 7:09 AM, Ethan Furman  wrote:
>
>> On 11/30/2016 02:32 AM, Jelte Fennema wrote:
>>
>> It would be nice to have a supported way to add defaults to namedtuple,
>>>  so the slightly hacky solution here does not have to be used:
>>>  http://stackoverflow.com/a/18348004/2570866
>>>
>>
>> Actually, the solution right below it is better [1]:
>>
>> --> from collections import namedtuple
>> --> class Node(namedtuple('Node', ['value', 'left', 'right'])):
>> --> __slots__ = ()
>> --> def __new__(cls, value, left=None, right=None):
>> --> return super(Node, cls).__new__(cls, value, left, right)
>>
>> But even more readable than that is using the NamedTuple class from my
>> aenum [3] library (and on SO as [3]):
>>
>> --> from aenum import NamedTuple
>> --> class Node(NamedTuple):
>> --> val = 0
>> --> left = 1, 'previous Node', None
>> --> right = 2, 'next Node', None
>>
>> shamelessly-plugging-my-own-solutions'ly yrs,
>>
>
> Ditto: with PEP 526 and the latest typing.py (in 3.6) you will be able to
> do this:
>
> class Employee(NamedTuple):
> name: str
> id: int
>
> We should make it so that the initial value in the class is used as the
> default value, too. (Sorry, this syntax still has no room for a docstring
> per attribute.)
>
> Implemented this in https://github.com/python/typing/pull/338

> --
> --Guido van Rossum (python.org/~guido )
>
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
___
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/