Re: [Python-ideas] Dictionary destructing and unpacking.

2017-06-07 Thread Matt Gilson
On Wed, Jun 7, 2017 at 3:11 PM, Erik  wrote:

> On 07/06/17 19:14, Nick Humrich wrote:
>
>> a, b, c = mydict.unpack('a', 'b', 'c')
>>
>
> def retrieve(mapping, *keys):
>return (mapping[key] for key in keys)
>
>
>
Or even:

from operator import itemgetter

retrieve = itemgetter('a', 'b', 'c')

a, b, c = retrieve(dictionary)


>
> $ python3
> Python 3.5.2 (default, Nov 17 2016, 17:05:23)
> [GCC 5.4.0 20160609] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>> def retrieve(mapping, *keys):
> ... return (mapping[key] for key in keys)
> ...
> >>> d = {'a': 1, 'b': None, 100: 'Foo' }
> >>> a, b, c = retrieve(d, 'a', 'b', 100)
> >>> a, b, c
> (1, None, 'Foo')
>
>
> E.
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>



-- 

Matt Gilson | Pattern

Software Engineer
getpattern.com
<https://www.getpattern.com?utm_source=email&utm_medium=email&utm_campaign=signature-matt>
___
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] dict(default=int)

2017-05-29 Thread Matt Gilson
On Mon, May 29, 2017 at 11:59 AM, Neil Girdhar 
wrote:

> A long time ago, I proposed that the dict variants (sorteddict,
> defaultdict, weakkeydict, etc.) be made more discoverable by having them
> specified as keyword arguments and I got the same feedback that the poster
> here is getting.  Now, instead of moving these classes into dict, why not
> have a factory like
>
> dict.factory(values=None, *, ordered=True, sorted=False,
> has_default=False, weak_keys=False, weak_values=False, …)
>

Hmm ... I don't think that I like this.  For one, it greatly increases the
amount of surface area that needs to be maintained in the standard
library.  As far as I know, we don't currently have a
OrderedWeakKeyDictionary with defaultdict behavior.  If this was to be
added, then each of the combinations of input keyword arguments would need
to be supported.  Many of them probably don't have very compelling
use-cases or they might not have semantics that would be easy to agree upon
a "preferred behavior" (Assuming that a mythological SortedDict pops into
existence in the standard lib, what happens if you call
`dict.factory(sorted=True, ordered=True)`?).  Of course, this sets a
precedence that future dict subclasses need to be added to the
`dict.factory` constructor as well which risks a very bloated signature
(or, someone has to make the decision about which subclasses should be
available and which should be left off ...).  This last argument can
repurposed against providing easy access to builtin dict subclasses via
their own methods (`dict.defaultdict(...)`).

I don't find very cumbersome to import the dict subclasses that I need from
the locations where they live.  I like that it forces me to be explicit and
I think that it generally makes reading the code easier in the normal cases
(`defaultdict(in)` vs. `dict.factory(default=int)`).  Of course, if someone
finds this idea particularly interesting, they could definitely explore the
idea more by creating a package on pypi that attempts to provide this
factory function.  If it got usage, that might go a long way to convincing
us nay-sayers that this idea has legs :-).




>
> If prefers the keyword-argument as options to the keyword-argument as
> initializer magic, they can set:
>
> dict = dict.factory
>
> Best,
>
> Neil
>
> On Thursday, March 9, 2017 at 5:58:43 PM UTC-5, Chris Barker wrote:
>>
>>
>>
>> >If we really want to make defaultdict feel more "builtin" (and I don't
>>> see
>>> >any reason to do so), I'd suggest adding a factory function:
>>> >
>>> >dict.defaultdict(int)
>>>
>>
>>
>>> Nice.
>>>
>>
>> I agree -- what about:
>>
>> dict.sorteddict() ??
>>
>> make easy access to various built-in dict variations...
>>
>> -CHB
>>
>>
>> --
>>
>> Christopher Barker, Ph.D.
>> Oceanographer
>>
>> Emergency Response Division
>> NOAA/NOS/OR&R(206) 526-6959   voice
>> 7600 Sand Point Way NE   (206) 526-6329   fax
>> Seattle, WA  98115   (206) 526-6317   main reception
>>
>> chris@noaa.gov
>>
>
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
>


-- 

Matt Gilson | Pattern

Software Engineer
getpattern.com
<https://www.getpattern.com?utm_source=email&utm_medium=email&utm_campaign=signature-matt>
___
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] Augmented assignment syntax for objects.

2017-04-25 Thread Matt Gilson
On Tue, Apr 25, 2017 at 4:31 PM, Erik  wrote:

> On 25/04/17 22:15, Brice PARENT wrote:
>
>> it may be easier to get something like this
>> (I think, as there is no new operator involved) :
>>
>
> No new operator, but still a syntax change, so that doesn't help from that
> POV.
>
>
>> def __init__(self, *args, **kwargs):
>>   self.* = *args
>>   self.** = **kwargs
>>
>
> What is "self.* = *args" supposed to do? For each positional argument,
> what name in the object is it bound to?
>
> E.


For what it's worth, that's what I don't really like about the initially
proposed syntax too ...

self .= foo, bar, baz

works OK, but:

tup = foo, bar, baz
self .= tup

doesn't work.  Admittedly, that could be part of the definition of this
feature, but it feels really unexpected to all of a sudden give my tuple a
temporary name and have the code behave in a dramatically different fashion.


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



-- 

Matt Gilson | Pattern

Software Engineer
getpattern.com
<https://www.getpattern.com?utm_source=email&utm_medium=email&utm_campaign=signature-matt>
___
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] get() method for list and tuples

2017-03-03 Thread Matt Gilson
On Fri, Mar 3, 2017 at 1:35 PM, Michel Desmoulin 
wrote:

>
>
> Le 03/03/2017 à 22:21, Chris Barker a écrit :
> > On Fri, Mar 3, 2017 at 12:21 PM, Sven R. Kunze  > > wrote:
> >
> >> For my part, I think casting a list to a dict is often the RIGHT
> >> way to address these issues.
> >
> > You can't be serious about this. Especially because it would negate
> > your response to Ed "conditional on a len() call is the way to go".
> > Now you tell people to use "convert to dict".
> >
> >
> > I am serious. It depends on the use case. If the data are an
>
> But that's the all problem isn't it?
>
> Since the start of the discussion, contesters have been offering
> numerous solutions, all being contextual and with gotchas, none being
> obvious, simple or elegant.
>
> The best is still try/except.
>

Which really isn't a big deal if you use it in one or two places.  If you
use it everywhere, it's not too hard to roll your own helper function.


>
> "There should be one obvious way to do it" right?
>
> Plus Sven already estimated the implementation would not be very hard.
> So we have one obvious solution to a problem that:
>
> - several professional programmers said they have
> - has a similar API in another built-in
>

You state that like it's a good thing ;-).  I'm not quite so sure.


> - has currently no elegant solutions
>
> The proposal is actionable, the cost of it seems low, and it's not
> remotely controversial.
>

It seems to be pretty controversial to me :-).


>
> Honestly what evil would happen if it's get accepted ?


Lots of things.  For one thing, when scanning a function, if I see
something with a `.get` method I generally think that it is probably a
Mapping.  Obviously that assumption may be wrong, but it's at least a good
place to start.  If this gets accepted, that's no longer a clear starting
assumption.

It breaks backward compatibility (in small ways).  People might be relying
on the presence/absence of a `.get` method in order to make their function
polymorphic in some convoluted way which would break when this change is
introduced.  (I'm not saying that would be a good programming design idea
-- and it might not hold water as an argument when real-world usage is
looked at but it should be at least investigated before we claim that this
change isn't going to hurt anybody).

It's also not clear to me why we should be singling out `tuple` and
`list`.  Why not `str`, `bytes` and other sequences?  Maybe it isn't that
useful on those types, but I'd argue that it's not really useful on `tuple`
either other than to keep the "`tuple` is an immutable `list`" paradigm.


>
>
___
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] For/in/as syntax

2017-03-03 Thread Matt Gilson
l len() or
> enumerate()
> #(but I could easily be wrong on that)
>
>
> ##
> # forloop.length when we broke out of the list
>
> small_and_medium_dogs_count = 0
> for dog in generate_dogs_list_by_size():
> if dog.size >= medium_dog_size:
> break
>
> small_and_medium_dogs_count += 1
>
> print("That's a total of {} small to medium dogs !".format(
> small_and_medium_dogs_count))
>
> # would be equivalent to
>
> for dog in generate_dogs_list_by_size() as dogs_loop:
> if dog.size >= medium_dog_size:
> break
>
> print("That's a total of {} small to medium dogs !".format(
> dogs_loop.length - 1))
>
> # -> easier to read, less temporary variables
>
> ##
> # forloop.break(), to break out of nested loops (or explicitly out of
> current
> #loop) - a little like pep-3136's first proposal
>
> has_dog_named_rex = False
> for owner in owners:
> for dog in dogs:
> if dog.name == "Rex":
> has_dog_named_rex = True
> break
>
> if has_dog_named_rex:
> break
>
> # would be equivalent to
>
> for owner in owners as owners_loop:
> for dog in dogs:  # syntax without "as" is off course still supported
> if dog.name == "Rex":
> owners_loop.break()
>
> # -> way easier to read and understand, less temporary variables
>
> ##
> # forloop.continue(), to call "continue" from any nested loops (or
> explicitly
> #in active loop)
>
> has_dog_named_rex = False
> for owner in owners:
> for dog in owner.dogs:
> if dog.name == "Rex":
> has_dog_named_rex = True
> break
>
> if has_dog_named_rex:
> continue
>
> # do something
>
> # would be equivalent to
>
> for owner in owners as owners_loop:
> for dog in owner.dogs:
> if dog.name == "Rex":
> owners_loop.continue()
>
> # do something
>
> # -> way easier to read and understand, less temporary variables
>
> ##
> # forloop.completed, to know if the list was entirely consumed or "break"
> was
> #called (or exception caught) - might help with the for/except/elseproposal
>
> broken_out = False
> for dog in dogs:
> if dog.name == "Rex":
> broken_out = True
> break
>
> if broken_out:
> print("We didn't consume all the dogs list")
>
> # would be equivalent to
>
> for dog in dogs as dogs_loop:
> if dog.name == "Rex":
> break
>
> if not dogs_loop.completed:
> print("We didn't consume all the dogs list")
>
> # -> less temporary variables, every line of code is relevant, easy to
> #understand
>
> ##
> # forloop.skip
> # In the example, we want to skip 2 elements starting from item #2
>
> skip = 0
> for num, dog in enumerate(dogs):
> if skip:
> skip -= 1
> continue
>
> if num == 2:
> skip = 2
>
> # would be equivalent to
>
> for dog in dogs as dogs_loop:
> if dogs_loop.counter == 2:
> dogs_loop.skip(2)
>
> # -> way easier to read and understand, less temporary variables
>
> # Notes :
> #- Does a call to forloop.skip() implies a forloop.continue() call or
> does
> #  the code continue its execution until the end of the loop, which
> will
> #  then be skipped? Implying the .continue() call seems less ambiguous
> to
> #  me. Or the method should be called skip_next_iteration, or something
> #  like that.
> #- Does a call to forloop.skip(2) adds 2 to forloop.length or not?
> # -> kwargs may be added to allow both behaviours for both questions.
>
> # We could allow the argument to be a function that accepts a single
> argument
> #and return a boolean, like
> dogs_loop.skip(lambda k: k % 3 == 0)  # Execute the code on multiples of 3
> only
>
>
> ##
>
> Thoughts :
> - It would allow to pass forloop.break and forloop.continue as callback to
>   other functions. Not sure yet if it's a good or a bad thing (readability
>   against what it could offer).
> - I haven't yet used much the asynchronous functionalities, so I couldn't
> yet
>   think about the implications of such a new syntax to this (and w

Re: [Python-ideas] Expose a child factory using MappingProxyType in builtins

2017-02-28 Thread Matt Gilson
I've implemented `frozendict` a few times for various projects and never
knew about MappingProxyType.  I always used `collections.abc.Mapping` ...


On Tue, Feb 28, 2017 at 9:12 AM, David Mertz  wrote:

> The difference in hits might be because MappingProxyType has a funny name
> and is in a hidden-ish location.  I.e. not necessarily because it *would
> be* less used or useful if it were more exposed.
>
>
It also might be because you can use `frozenset` in python2.x code -- And
there's lots of that lying around...


> In either case, the name that makes sense to me would be `frozendict`.
> That could very well live in `collections` of course.
>

Yes, I agree.  Though it'd also probably need to be hashable if we were to
give it that name.  I'm not 100% sure that `MappingProxyType` works there
as it's just a view into another mapping.  If the first mapping changes, so
does the hash.  This is the same problem we have hashing tuple in some
sense -- But tuple can say "Nope, sorry.  I can't hash this because it's
got an unhashable member".  I don't think we can really do the same thing
with a MappingProxy since most of the time, it'll be constructed from
something else.  I suppose the workaround is pretty simple though:

class frozendict(MappingProxyType):
def __init__(self, proxy):
super().__init__(proxy.copy())  # Copy the proxy! -- Maybe need
`copy.copy()` instead?
def __hash__(self):
return hash(frozenset(self.items()))

This could likely be done better, but hopefully it gets the idea across...


>
> On Tue, Feb 28, 2017 at 7:40 AM, Ivan Levkivskyi 
> wrote:
>
>> Searching MappingProxyType on GitHub gives over 10,000 results.
>> I think it probably makes sense to make mappingproxy more "visible",
>> maybe move it to collections module? (where OrderedDict lives)
>>
>> I am not sure if it makes sense to move it to builtins. (for comparison
>> frozenset gives around 1000,000 results)
>>
>> --
>> Ivan
>>
>>
>>
>> On 28 February 2017 at 16:24, Joseph Hackman 
>> wrote:
>>
>>> +1
>>>
>>> I think this makes a lot of sense. What would you name the built in?
>>>
>>> -Joseph
>>>
>>> > On Feb 28, 2017, at 7:17 AM, Michel Desmoulin <
>>> desmoulinmic...@gmail.com> wrote:
>>> >
>>> > We have the immutable frozenset for sets and and tuples for lists.
>>> >
>>> > But we also have something to manipulate dict as immutable
>>> datastructures:
>>> >
>>> >>>> from types import MappingProxyType as idict
>>> >>>> d = idict({'a':1, 'b':2, 'c':3})
>>> >>>> d['a'] = 4
>>> > Traceback (most recent call last):
>>> >  File "", line 1, in 
>>> >d['a'] = 4
>>> > TypeError: 'mappingproxy' object does not support item assignment
>>> >
>>> > We could expose this as a built type to allow the last of the most
>>> > important data structure in Python to be easily immutable.
>>> >
>>> > ___
>>> > 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/
>>
>
>
>
> --
> Keeping medicines from the bloodstreams of the sick; food
> from the bellies of the hungry; books from the hands of the
> uneducated; technology from the underdeveloped; and putting
> advocates of freedom in prisons.  Intellectual property is
> to the 21st century what the slave trade was to the 16th.
>
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>



-- 

[image: pattern-sig.png]

Matt Gilson // SOFTWARE ENGINEER

E: m...@getpattern.com // P: 603.892.7736

We’re looking for beta testers.  Go here
<https://www.getpattern.com/meetpattern> to sign up!
___
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: Define a method or function attributeoutsideof a class with the dot operator

2017-02-13 Thread Matt Gilson
For whatever weight my opinion holds, I'm +0 on this one.  In my
estimation, in an ideal world it seems like:

class Foo(object):
 def bar(self):
 """Bar!"""


# Identical to:

class Foo(object): pass

def Foo.bar(self):
"""Bar!"""

But I think that's going to be hard to achieve given implicit binding of
`super` (as some have already mentioned) and more mind-bendingly when
user-defined metaclasses are in play.  Indeed, with metaclasses, it seems
like it become impossible to actually guarantee the equality of the above
two blocks of code.  Maybe the PEP writers are OK with that, but that
should be decided at the outset...

Also note that if users start adopting this as their default mode of class
creation (rather than just *class extending*), code-folding in a lot of
IDEs won't handle it gracefully (at least not for quite a while).

On Mon, Feb 13, 2017 at 11:32 AM, Joseph Hackman 
wrote:

> Generally speaking, I'm +1 on this idea, I think it would make code more
> readable, especially for tools like IDEs.
>
> I just wanted to ask: can someone point me to the reason Python doesn't
> support referencing a class inside it's own definition? It seems like that
> would solve some of the cases discussed here, and with Type hinting that
> seems like something that maybe should be considered?
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>



-- 

[image: pattern-sig.png]

Matt Gilson // SOFTWARE ENGINEER

E: m...@getpattern.com // P: 603.892.7736

We’re looking for beta testers.  Go here
<https://www.getpattern.com/meetpattern> to sign up!
___
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] incremental hashing in __hash__

2017-01-05 Thread Matt Gilson
I agree with Paul -- I'm not convinced that this is common enough or that
the benefits are big enough to warrant something builtin.  However, I did
decide to dust off some of my old skills and I threw together a simple gist
to see how hard it would be to create something using Cython based on the
CPython tuple hash algorithm.  I don't know how well it works for arbitrary
iterables without a `__length_hint__`, but seems to work as intended for
iterables that have the length hint.


https://gist.github.com/mgilson/129859a79487a483163980db25b709bf

If you're interested, or want to pick this up and actually do something
with it, feel free... Also, I haven't written anything using Cython for
ages, so if this could be further optimized, feel free to let me know.

On Thu, Jan 5, 2017 at 7:58 AM, Paul Moore  wrote:

> On 5 January 2017 at 13:28, Neil Girdhar  wrote:
> > The point is that the OP doesn't want to write his own hash function, but
> > wants Python to provide a standard way of hashing an iterable.  Today,
> the
> > standard way is to convert to tuple and call hash on that.  That may not
> be
> > efficient. FWIW from a style perspective, I agree with OP.
>
> The debate here regarding tuple/frozenset indicates that there may not
> be a "standard way" of hashing an iterable (should order matter?).
> Although I agree that assuming order matters is a reasonable
> assumption to make in the absence of any better information.
>
> Hashing is low enough level that providing helpers in the stdlib is
> not unreasonable. It's not obvious (to me, at least) that it's a
> common enough need to warrant it, though. Do we have any information
> on how often people implement their own __hash__, or how often
> hash(tuple(my_iterable)) would be an acceptable hash, except for the
> cost of creating the tuple? The OP's request is the only time this has
> come up as a requirement, to my knowledge. Hence my suggestion to copy
> the tuple implementation, modify it to work with general iterables,
> and publish it as a 3rd party module - its usage might give us an idea
> of how often this need arises. (The other option would be for someone
> to do some analysis of published code).
>
> Assuming it is a sufficiently useful primitive to add, then we can
> debate naming. But I'd prefer it to be named in such a way that it
> makes it clear that it's a low-level helper for people writing their
> own __hash__ function, and not some sort of variant of hashing (which
> hash.from_iterable implies to me).
>
> Paul
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>



-- 

[image: pattern-sig.png]

Matt Gilson // SOFTWARE ENGINEER

E: m...@getpattern.com // P: 603.892.7736

We’re looking for beta testers.  Go here
<https://www.getpattern.com/meetpattern> to sign up!
___
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] incremental hashing in __hash__

2017-01-05 Thread Matt Gilson
possible. But it breaks backwards-compatability and
>> introduces something which I consider to be an unclean API (calling a
>> dunder method directly). Unless there's a *really* strong advantage to
>>
>> tuple.__hash__(...)
>>
>> over
>>
>> hash.from_iterable(...)
>>
>> (or equivalent), I would be against this change.
>>
>>
>>
>> > (And similarly with frozenset.__hash__(), so that the fast C
>> > implementation of that algorithm could be used, rather than the slow
>> > collections.Set._hash() implementation. Then the duplicated
>> implementation
>> > in _collections_abc.py's Set._hash() could be removed completely,
>> > delegating to frozenset.__hash__() instead.)
>>
>> This is a good point. Until now, I've been assuming that
>> hash.from_iterable should consider order. But frozenset shows us that
>> sometimes the hash should *not* consider order.
>>
>> This hints that perhaps the hash.from_iterable() should have its own
>> optional dunder method. Or maybe we need two functions: an ordered
>> version and an unordered version.
>>
>> Hmmm... just tossing out a wild idea here... let's get rid of the dunder
>> method part of your suggestion, and add new public class methods to
>> tuple and frozenset:
>>
>> tuple.hash_from_iter(iterable)
>> frozenset.hash_from_iter(iterable)
>>
>>
>> That gets rid of all the objections about backwards compatibility, since
>> these are new methods. They're not dunder names, so there are no
>> objections to being used as part of the public API.
>>
>> A possible objection is the question, is this functionality *actually*
>> important enough to bother?
>>
>> Another possible objection: are these methods part of the sequence/set
>> API? If not, do they really belong on the tuple/frozenset? Maybe they
>> belong elsewhere?
>>
>>
>>
>> > Would this API more cleanly communicate the algorithm being used and
>> the
>> > implementation,
>>
>> No. If you want to communicate the algorithm being used, write some
>> documentation.
>>
>> Seriously, the public API doesn't communicate the algorithm used for the
>> implementation. How can it? We can keep the same interface and change
>> the implementation, or change the interface and keep the implementation.
>> The two are (mostly) independent.
>>
>>
>>
>> > while making a smaller increase in API surface area
>> > compared to introducing a new function?
>>
>> It's difficult to quantify "API surface area". On the one hand, we have
>> the addition of one or two new functions or methods. Contrast with:
>>
>> * introducing a new kind of method into the built-ins (one which
>>   behaves like a classmethod when called from the class, and like
>>   an instance method when called from an instance);
>>
>> * changing tuple.__hash__ from an ordinary method to one of the
>>   above special methods;
>>
>> * and likewise for frozenset.__hash__;
>>
>> * change __hash__ from "only used as implementation, not as
>>   interface" to "sometimes used as interface".
>>
>>
>> To me, adding one or two new methods/functions is the smaller, or at
>> least less disruptive, change.
>>
>>
>>
>> --
>> Steve
>> ___
>> Python-ideas mailing list
>> python...@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/
>



-- 

[image: pattern-sig.png]

Matt Gilson // SOFTWARE ENGINEER

E: m...@getpattern.com // P: 603.892.7736

We’re looking for beta testers.  Go here
<https://www.getpattern.com/meetpattern> to sign up!
___
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] Enhancing vars()

2016-12-13 Thread Matt Gilson



> It also refers to local and global variables, as vars() is effectively
> an alias for locals() if you don't pass an argument, and locals() is
> effectively an alias for globals() at module level:
>
> https://www.getpattern.com/meetpattern> to sign up!
___
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] Null coalescing operator

2016-11-02 Thread Matt Gilson
I actually think that Zero's point here is quite valid... At some earlier
point in the thread, I believe that Nick Coughlin was saying that we should
be asking ourselves _why_ we want to do something like this and the result
of that discussion was because there is pain when working with
"pseudo-structured" responses from various APIs.  This use-case resonates
with me as I work with JSON responses quite frequently.

The thing about "pseudo-structured" data is that there isn't an agreed upon
way to represent it.  While one API might send a field with a `null` value
in some cases, another API might send a field with no data (after all, why
bother putting it in the response if it's going to be `null`?  You're just
wasting bytes on the wire).  As a concrete case where fields are truly
missing -- Most of the Google APIs accept a "fields" parameter that allows
you to pair down what is actually included in the response (If you don't
believe me, feel free to play around with it in their API explorer --
https://developers.google.com/google-apps/calendar/v3/reference/calendars/get
).

So, while this proposal is specifically about a "Null coalescing operator",
my guess is that users will think of it as a "Get the field if it exists,
else short-circuit and return `None`".  And it might take a lot of
education to try to get everyone aligned on the same page around what the
"if it exists" actually means.  At first, I was thinking that perhaps
_adding_ an operator would help the community to standardize around "If the
field is missing, then put a `None` in there -- But unfortunately, I think
that the JSON API example demonstrates that a really big use-case for this
operator is in working with APIs that are likely written in different
languages whose communities frequently don't follow the same norms that
python has embraced.

I suppose that the suggestion would be to write:

foo.get('bar')?['baz']

if the `foo` dict may or may not have ` bar` key?


On Wed, Nov 2, 2016 at 3:22 PM, Greg Ewing 
wrote:

> Zero Piraeus writes:
>
>>
>> If I write something like obj.attr, the failure mode I care about is
>> that
>> obj has no attribute attr, rather than that obj is specifically None
>> (or
>> one of a defined group of somewhat Nonelike objects).
>>
>> Clearly, in such a circumstance, obj is not what I expected it to be,
>> because I thought it was going to have an attribute attr, and it
>> doesn't.
>>
>
> If it's an error, you shouldn't be trying to do anything
> about it, just let the exception happen.
>
> The proposed .? syntax is designed for cases where it's *not*
> an error for the object to be missing the attribute, *and*
> the correct action in that situation is to skip whatever
> you would have done otherwise.
>
> What needs to be decided is whether such use cases are frequent
> enough to justify special syntax.
>
> --
> Greg
>
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>



-- 

[image: pattern-sig.png]

Matt Gilson // SOFTWARE ENGINEER

E: m...@getpattern.com // P: 603.892.7736

We’re looking for beta testers.  Go here
<https://www.getpattern.com/meetpattern> to sign up!
___
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 multi-dimensional array constructor

2016-10-19 Thread Matt Gilson
FWIW, you probably _don't_ want to use `ndarray` directly.  Normally, you
want to use the `np.array` factory function...

>>> import numpy as np
>>> a = np.ndarray([0, 1, 2])
>>> a
array([], shape=(0, 1, 2), dtype=float64)

Aside from that, my main problem with this proposal is that it seems to
only be relevant when used in third party code.  There _is_ some precedence
for this (for example rich comparisons and the matrix multiplication
operator) -- However, these are all _operators_ so third party code can
hook into it using the provided hook methods.  This proposal is different
in that it _isn't_ proposing an operator, so there isn't any object on
which to define a magic hook method.  I think that it was mentioned that it
might be possible for a user to _register_ a callable that would then be
used when this syntax was envoked -- But having a global setting like that
leads to contention.  What if I want to use this syntax with `np.ndarray`
but some other third party code (that I want to use _with_ numpy_ tries to
hook into the syntax as well?  All of a sudden, my script stops working as
soon as I import a new third party module.

I _do_ think that this might be a valid proposal for some of the more
domain specific python variants (e.g. IPython) which have a pre-processing
layer on top of the rest of the language.  It might be worth trying to
float this idea in one of their ideas mailing lists/issue trackers.

On Wed, Oct 19, 2016 at 1:10 PM, Todd  wrote:

> On Wed, Oct 19, 2016 at 3:55 PM, Joseph Jevnik  wrote:
>
>> You could add or prototype this with quasiquotes (
>> http://quasiquotes.readthedocs.io/en/latest/). You just need to be able
>> to parse the body of your expression as a string into an array. Here is a
>> quick example with a parser that only accepts 2d arrays:
>>
>> ```
>> # coding: quasiquotes
>>
>> import numpy as np
>> from quasiquotes import QuasiQuoter
>>
>>
>> @object.__new__
>> class array(QuasiQuoter):
>> def quote_expr(self, expr, frame, col_offset):
>> return np.array([
>> eval('[%s]' % d, frame.f_globals, frame.f_locals)
>> for d in expr.split('||')
>> ])
>>
>>
>> def f():
>> a = 1
>> b = 2
>> c = 3
>> return [$array| a, b, c || 4, 5, 6 |]
>>
>>
>> if __name__ == '__main__':
>> print(f())
>> ```
>>
>
> Interesting project, thanks!  If there is any actual interest in this that
> might be a good way to prototype it.
>
>
>> Personally I am not sold on replacing `[` and `]` with `|` because I like
>> that you can visually see where dimensions are closed.
>>
>>
> Yes, that issue occurred to me.  But assuming a rectangular matrix, I had
> trouble coming up with a good example that is clearer than what you could
> do with this syntax.  For simple arrays it isn't needed, and complicated
> arrays are large so picking out the "[" and "]" becomes visually harder at
> least for me.  Do you have a specific example that you think would be
> clearer than what is possible with this syntax?
>
> Of course that is more of an issue with jagged arrays, but numpy doesn't
> support those and I am not aware of any plans to add them (dynd is another
> story).
>
> Also keep in mind that this would supplement the existing approach, it
> doesn't replace it.  np.ndarray() would stay around just like list() stays
> around for cases where it makes sense.
>
>
> ___
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>



-- 

[image: pattern-sig.png]

Matt Gilson // SOFTWARE ENGINEER

E: m...@getpattern.com // P: 603.892.7736

We’re looking for beta testers.  Go here
<https://www.getpattern.com/meetpattern> to sign up!
___
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] Shuffled

2016-09-07 Thread Matt Gilson
I lurk around here a lot more than I actually post -- But in this case I
find myself weighing in firmly on the side of "please don't add this".
It'd just add noise in the documentation and __builtins__ namespace.  There
are millions of useful functions that *could* be added to the `list` object
(or to the `__builtins__` namespace).  It's the job of the core dev team to
decide which are the most useful for everybody and this is one where (in my
opinion) the usefulness doesn't justify the additional clutter.

It seems like the primary argument for this is that some users would like
to have this functionality baked into an interactive session.  If that's
the case, then I'd like to point out that if you find yourself wanting this
in an interactive session frequently there is an interactive startup file
<https://docs.python.org/3/tutorial/appendix.html#the-interactive-startup-file>
that you can modify so that this function will always be available to
*you* whenever
you start up an interactive session (and you can put whatever else in there
that you like as well :-).

I hope that helps.

On Wed, Sep 7, 2016 at 3:22 PM, Sven R. Kunze  wrote:

> Maybe, there's a misunderstanding here and I hope I didn't waste too much
> of your and my time.
>
> Not sure where I got this from but my last status was that Arek would like
> to have a "shuffled" function that does exactly what you described. Maybe,
> that doesn't fit the reports description but his pull request will tell the
> truth. :)
>
>
> About the confusion of returning None. It's not confusing in the sense of
> "o my god, I did it wrong, I need to learn it", but more, like "I used
> shuffle, BECAUSE it's the only one I could find in a hurry" and then
> ascertain "why the heck is there no alternative returning the shuffled
> result instead of overwriting my list? I would expect this from Python as
> it already provides both alternatives for sorting".
>
>
> Sven
>
>
>
> On 08.09.2016 00:02, Tim Peters wrote:
>
>> [Sven R. Kunze ]
>>
>>> I am not questioning experience which everyone in a team can benefit
>>> from.
>>>
>>>
>>> BUT experienced devs also need to recognize and respect the fact that
>>> younger/unexperienced developers are just better in detecting
>>> inconsistencies and bloody work-arounds. They simply haven't had to live
>>> with them for so long. Experienced devs just are stuck in a rut/are
>>> routine-blinded: "we've done that for years", "there's no better way".
>>>
>>>
>>> That's the way we do it in our teams. Employing the new guys as some
>>> sort of
>>> inconsistency detectors. This way, they learn to find their way around
>>> the
>>> code base and they can improve it by doing so.
>>>
>>> And I would never allow it in my team, to dismiss this kind of
>>> observation
>>> from new colleagues. It's invaluable as they will become routine-blinded
>>> as
>>> well.
>>>
>> I have been more than willing to discuss it, and I did not close the
>> issue report.  I did say I was opposed to it, but that's simply
>> because I am, and I explained there too _why_ I was opposed.
>>
>> Do you have anything to say about the specific proposal?  I doubt
>> either of us has found this meta-discussion useful.  I'm still looking
>> for a compelling use case.  The only concrete thing anyone has noted
>> in `shuffled()`'s favor so far is that sometimes they're surprised by
>> the behavior of random.shuffle(list) returning None in an interactive
>> shell (noted by you, and by another, and I cheerfully own up to being
>> a bit surprised by that too long ago).   But that's an observation
>> about `random.shuffle()`, not about the proposed `shuffled()`.
>>
>>
>> [...] I would be far more annoyed if, e.g.,
>>>>
>>>> random.shuffle(some_million_element_list)
>>>>>>>
>>>>>>   swamped my terminal with mountains of output.
>>>>
>>> But you readily accept this behavior for "sorted"? That makes no sense at
>>> all.
>>>
>> Of course it does.  The only analogy to random.shuffle(big_list)
>> returning None that makes a lick of sense here is that big_list.sort()
>> also returns None.  IF a `shuffled()` function is introduced, then of
>> course it should return its result - just like `sorted()` returns its
>> result.
>>
>>
>> You can&#