Re: Returning from a multiple stacked call at once

2020-12-15 Thread jak

Il 12/12/2020 18:20, Dieter Maurer ha scritto:

ast wrote at 2020-12-12 07:39 +0100:

In case a function recursively calls itself many times,
is there a way to return a data immediately without
unstacking all functions ?


Python does not have "long jump"s (out of many functions, many loop
incarnations).
In some cases, you can use exceptions to emulate "long jump"s.



I don't know what you mean by 'emulating' because using the exception 
handler you simply defer unstacking to it. The real problem is that if 
you write a function that ends by calling itself and does not take 
advantage of the branch of code following the recursive call, then it is 
a wrong way to use a recursive function which should be replaced with a 
simple one containing a loop where you can insert a break statement 
wherever you like. IMHO


Greetings.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Returning from a multiple stacked call at once

2020-12-15 Thread jak

Il 15/12/2020 10:41, jak ha scritto:

Il 12/12/2020 18:20, Dieter Maurer ha scritto:

ast wrote at 2020-12-12 07:39 +0100:

In case a function recursively calls itself many times,
is there a way to return a data immediately without
unstacking all functions ?


Python does not have "long jump"s (out of many functions, many loop
incarnations).
In some cases, you can use exceptions to emulate "long jump"s.



I don't know what you mean by 'emulating' because using the exception 
handler you simply defer unstacking to it. The real problem is that if 
you write a function that ends by calling itself and does not take 
advantage of the branch of code following the recursive call, then it is 
a wrong way to use a recursive function which should be replaced with a 
simple one containing a loop where you can insert a break statement 
wherever you like. IMHO


Greetings.



this could be a way to emulate a long_jump:

def f(i):
if i < 10:
i += 1
yield from f(i)
else:
yield i

i = 0
retult = 0
for n in f(i):
result = n
break
print(result)

--
https://mail.python.org/mailman/listinfo/python-list


Re: Returning from a multiple stacked call at once

2020-12-15 Thread Chris Angelico
On Tue, Dec 15, 2020 at 9:56 PM jak  wrote:
>
> this could be a way to emulate a long_jump:
>
> def f(i):
>  if i < 10:
>  i += 1
>  yield from f(i)
>  else:
>  yield i
>
> i = 0
> retult = 0
> for n in f(i):
>  result = n
>  break
> print(result)
>

Note that this requires just as much cooperation as this version does:

def f(i):
if i < 10:
return f(i + 1)
return i

result = f(0)

The only difference is that "yield from" sorta kinda gives you a
"maybe return", but you're not actually using that in your example, so
it doesn't showcase that. But let's say you're searching a complex
data structure for something:

def find(obj, pred):
if pred(obj): yield obj
if isinstance(obj, list):
for elem in obj: yield from find(elem, pred)
if isinstance(obj, dict):
for elem in obj.values(): yield from find(elem, pred)

Taking the first matching element could be done without worrying too
much about whether any subsequent elements would match. I wouldn't
really call this a "long jump", though; this is a lazy filter that can
be efficiently used to locate the first few results without
calculating them all.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Returning from a multiple stacked call at once

2020-12-15 Thread jak

Il 12/12/2020 07:39, ast ha scritto:

Hello

In case a function recursively calls itself many times,
is there a way to return a data immediately without
unstacking all functions ?



try this way:

def path_finder(graph, start, end, path=[]):
if start in path:
yield None
if start == end:
yield path + [start]  # Found !
if start not in graph:
yield None

path = path + [start]

for node in graph[start]:
found_path = yield from path_finder(graph, node, end, path)
if found_path:
yield found_path
yield None


graph = {'A': ['B', 'C'],
 'B': ['C', 'D'],
 'C': ['D'],
 'D': ['C'],
 'E': ['F'],
 'F': ['C']}
result = []
for r in path_finder(graph, 'A', 'D'):
result = r
break
print(result)
--
https://mail.python.org/mailman/listinfo/python-list


Re: Returning from a multiple stacked call at once

2020-12-15 Thread jak

Il 15/12/2020 12:25, Chris Angelico ha scritto:

On Tue, Dec 15, 2020 at 9:56 PM jak  wrote:


this could be a way to emulate a long_jump:

def f(i):
  if i < 10:
  i += 1
  yield from f(i)
  else:
  yield i

i = 0
retult = 0
for n in f(i):
  result = n
  break
print(result)



Note that this requires just as much cooperation as this version does:

def f(i):
 if i < 10:
 return f(i + 1)
 return i

result = f(0)

The only difference is that "yield from" sorta kinda gives you a
"maybe return", but you're not actually using that in your example, so
it doesn't showcase that. But let's say you're searching a complex
data structure for something:

def find(obj, pred):
 if pred(obj): yield obj
 if isinstance(obj, list):
 for elem in obj: yield from find(elem, pred)
 if isinstance(obj, dict):
 for elem in obj.values(): yield from find(elem, pred)

Taking the first matching element could be done without worrying too
much about whether any subsequent elements would match. I wouldn't
really call this a "long jump", though; this is a lazy filter that can
be efficiently used to locate the first few results without
calculating them all.

ChrisA



You are right. In fact I used the word 'emulate' to mean that this is 
what (IMO) comes closest to a long jump.


Cheers.
--
https://mail.python.org/mailman/listinfo/python-list


SQLObject 3.9.0

2020-12-15 Thread Oleg Broytman
Hello!

I'm pleased to announce version 3.9.0, the first release
of branch 3.9 of SQLObject.


What's new in SQLObject
===

Contributors for this release are:

+ Michael S. Root, Ameya Bapat - ``JSONCol``;

+ Jerry Nance - reported a bug with ``DateTime`` from ``Zope``.

Features


* Add ``JSONCol``: a universal json column that converts simple Python objects
  (None, bool, int, float, long, dict, list, str/unicode to/from JSON using
  json.dumps/loads. A subclass of StringCol. Requires ``VARCHAR``/``TEXT``
  columns at backends, doesn't work with ``JSON`` columns.

* Extend/fix support for ``DateTime`` from ``Zope``.

* Drop support for very old version of ``mxDateTime``
  without ``mx.`` namespace.

Drivers
---

* Support `mariadb `_.

CI
--

* Run tests with Python 3.9 at Travis and AppVeyor.

For a more complete list, please see the news:
http://sqlobject.org/News.html


What is SQLObject
=

SQLObject is an object-relational mapper.  Your database tables are described
as classes, and rows are instances of those classes.  SQLObject is meant to be
easy to use and quick to get started with.

It currently supports MySQL, PostgreSQL and SQLite; connections to other
backends - Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB) - are
lesser debugged).

Python 2.7 or 3.4+ is required.


Where is SQLObject
==

Site:
http://sqlobject.org

Development:
http://sqlobject.org/devel/

Mailing list:
https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss

Download:
https://pypi.org/project/SQLObject/3.9.0

News and changes:
http://sqlobject.org/News.html

StackOverflow:
https://stackoverflow.com/questions/tagged/sqlobject


Example
===

Create a simple class that wraps a table::

  >>> from sqlobject import *
  >>>
  >>> sqlhub.processConnection = connectionForURI('sqlite:/:memory:')
  >>>
  >>> class Person(SQLObject):
  ... fname = StringCol()
  ... mi = StringCol(length=1, default=None)
  ... lname = StringCol()
  ...
  >>> Person.createTable()

Use the object::

  >>> p = Person(fname="John", lname="Doe")
  >>> p
  
  >>> p.fname
  'John'
  >>> p.mi = 'Q'
  >>> p2 = Person.get(1)
  >>> p2
  
  >>> p is p2
  True

Queries::

  >>> p3 = Person.selectBy(lname="Doe")[0]
  >>> p3
  
  >>> pc = Person.select(Person.q.lname=="Doe").count()
  >>> pc
  1

Oleg.
-- 
Oleg Broytmanhttps://phdru.name/[email protected]
   Programmers don't die, they just GOSUB without RETURN.
-- 
https://mail.python.org/mailman/listinfo/python-list


Library for text substitutions with calculations?

2020-12-15 Thread Jan Erik Moström
I want to do some text substitutions but a bit more advanced than what 
string.Template class can do. I addition to plain text substitution I 
would like to be able to do some calculations:


$value+1 - If value is 16 this would insert 17 in the text. I would also 
like to subtract.


$value+1w - In this case value would be a date, this would add a week to 
that date, similar for year, month, hours. Also subtract.


The exact syntax isn't important.

In other words I would like to define

example1 = 12
example2 = 2020-12-15

and then some text:

Hello world $example1+10 and a date $example+1w

would result in

Hello world 22 and a date 2020-12-22

Is there some library that can do something like this?

I probably searching using the wrong keywords because I can't find 
anything.


= jem
--
https://mail.python.org/mailman/listinfo/python-list


Re: Library for text substitutions with calculations?

2020-12-15 Thread 2QdxY4RzWzUUiLuE
On 2020-12-15 at 16:04:55 +0100,
Jan Erik Moström  wrote:

> I want to do some text substitutions but a bit more advanced than what
> string.Template class can do. I addition to plain text substitution I would
> like to be able to do some calculations:
> 
> $value+1 - If value is 16 this would insert 17 in the text. I would also
> like to subtract.

[...]

A lot of libraries for making web pages can do things like that; a
starting point is .

HTH,
Dan
-- 
https://mail.python.org/mailman/listinfo/python-list


Python3 change logs

2020-12-15 Thread Rich Shepard

I've upgraded from Python-3.7.x to Python-3.9.x and want to learn about
differences (if any) in tkinter between the two versions.

Looking on the python.org web site I did not find change logs with the
sources or under the other menus I checked. Please point me to any available
logs.

Regards,

Rich
--
https://mail.python.org/mailman/listinfo/python-list


Re: Library for text substitutions with calculations?

2020-12-15 Thread Bob Gailer
On Tue, Dec 15, 2020, 10:42 AM <[email protected]> wrote:

> On 2020-12-15 at 16:04:55 +0100,
> Jan Erik Moström  wrote:
>
> > I want to do some text substitutions but a bit more advanced than what
> > string.Template class can do. I addition to plain text substitution I
> would
> > like to be able to do some calculations:
> >
> > $value+1 - If value is 16 this would insert 17 in the text. I would also
> > like to subtract.
>
> val = 2

print(f'{val+3}')

5

Bob Gailer
-- 
https://mail.python.org/mailman/listinfo/python-list


dict.get(key, default) evaluates default even if key exists

2020-12-15 Thread Mark Polesky via Python-list
Hi.

# Running this script

D = {'a':1}
def get_default():
    print('Nobody expects this')
    return 0
print(D.get('a', get_default()))

# ...generates this output:

Nobody expects this
1

###

Since I'm brand new to this community, I thought I'd ask here first... Is this 
worthy of a bug report?  This behavior is definitely unexpected to me, and I 
accidentally coded an endless loop in a mutual recursion situation because of 
it.  Calling dict.get.__doc__ only gives this short sentence: Return the value 
for key if key is in the dictionary, else default.  Nothing in that docstring 
suggests that the default value is evaluated even if the key exists, and I 
can't think of any good reason to do so.

Am I missing something?

Thanks,
Mark
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python3 change logs

2020-12-15 Thread Skip Montanaro
Change logs are kept as part of the source, I believe. Try browsing the
cpython GitHub repo:

https://github.com/python/cpython

Skip

On Tue, Dec 15, 2020, 10:05 AM Rich Shepard 
wrote:

> I've upgraded from Python-3.7.x to Python-3.9.x and want to learn about
> differences (if any) in tkinter between the two versions.
>
> Looking on the python.org web site I did not find change logs with the
> sources or under the other menus I checked. Please point me to any
> available
> logs.
>
> Regards,
>
> Rich
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python3 change logs

2020-12-15 Thread Skip Montanaro
Also, check www.python.org for "What's New" pages. I believe one is
generated for every release. It will be less detailed than change logs in
GitHub, but more reader friendly.

Skip
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python3 change logs

2020-12-15 Thread Skip Montanaro
Dang... I'm having very incomplete thoughts. Apologies for the multiple
replies when one would have sufficed.

https://docs.python.org/3/whatsnew/3.9.html

Skip
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: dict.get(key, default) evaluates default even if key exists

2020-12-15 Thread Dan Stromberg
On Tue, Dec 15, 2020 at 9:57 AM Mark Polesky via Python-list <
[email protected]> wrote:

> Hi.
>
> # Running this script
>
> D = {'a':1}
> def get_default():
> print('Nobody expects this')
> return 0
> print(D.get('a', get_default()))
>
> # ...generates this output:
>
> Nobody expects this
> 1
>
> ###
>
> Since I'm brand new to this community, I thought I'd ask here first... Is
> this worthy of a bug report?  This behavior is definitely unexpected to me,
> and I accidentally coded an endless loop in a mutual recursion situation
> because of it.  Calling dict.get.__doc__ only gives this short sentence:
> Return the value for key if key is in the dictionary, else default.
> Nothing in that docstring suggests that the default value is evaluated even
> if the key exists, and I can't think of any good reason to do so.
>

Python isn't a lazy language.  It's evaluating get_default()
unconditionally, prior to executing the D.get().  I don't think it's a
Python bug.

BTW, I tend to prefer collections.defaultdict over the two argument D.get
or setdefault.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: dict.get(key, default) evaluates default even if key exists

2020-12-15 Thread Chris Angelico
On Wed, Dec 16, 2020 at 4:58 AM Mark Polesky via Python-list
 wrote:
>
> Hi.
>
> # Running this script
>
> D = {'a':1}
> def get_default():
> print('Nobody expects this')
> return 0
> print(D.get('a', get_default()))
>
> # ...generates this output:
>
> Nobody expects this
> 1
>
> ###
>
> Since I'm brand new to this community, I thought I'd ask here first... Is 
> this worthy of a bug report?  This behavior is definitely unexpected to me, 
> and I accidentally coded an endless loop in a mutual recursion situation 
> because of it.  Calling dict.get.__doc__ only gives this short sentence: 
> Return the value for key if key is in the dictionary, else default.  Nothing 
> in that docstring suggests that the default value is evaluated even if the 
> key exists, and I can't think of any good reason to do so.
>
> Am I missing something?
>

Seems what you want is the __missing__ method. Look into it - I think
it will do what you're expecting here.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: dict.get(key, default) evaluates default even if key exists

2020-12-15 Thread Serhiy Storchaka
15.12.20 19:07, Mark Polesky via Python-list пише:
> # Running this script
> 
> D = {'a':1}
> def get_default():
>     print('Nobody expects this')
>     return 0
> print(D.get('a', get_default()))
> 
> # ...generates this output:
> 
> Nobody expects this
> 1
> 
> ###
> 
> Since I'm brand new to this community, I thought I'd ask here first... Is 
> this worthy of a bug report?  This behavior is definitely unexpected to me, 
> and I accidentally coded an endless loop in a mutual recursion situation 
> because of it.  Calling dict.get.__doc__ only gives this short sentence: 
> Return the value for key if key is in the dictionary, else default.  Nothing 
> in that docstring suggests that the default value is evaluated even if the 
> key exists, and I can't think of any good reason to do so.
> 
> Am I missing something?

You are missed that expressions for function arguments are always
evaluated before passing their values to a function. This is expected
behavior, and I can't remember any programming language in which it's
different.

So dict.get() returns the value of argument default, which is computed
by calling function get_default() before calling dict.get().

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python3 change logs

2020-12-15 Thread Rich Shepard

On Tue, 15 Dec 2020, Skip Montanaro wrote:


Change logs are kept as part of the source, I believe. Try browsing the
cpython GitHub repo:
https://github.com/python/cpython


Skip,

Thanks, I will.

Stay well,

Rich
--
https://mail.python.org/mailman/listinfo/python-list


Re: Python3 change logs

2020-12-15 Thread Rich Shepard

On Tue, 15 Dec 2020, Skip Montanaro wrote:


Also, check www.python.org for "What's New" pages. I believe one is
generated for every release. It will be less detailed than change logs in
GitHub, but more reader friendly.


Skip,

I don't find a "What's New" page, but under Download -> All Releases (rather
than Source code) there's a column of Release Notes for each version. I'll
check github, too.

Thanks,

Rich
--
https://mail.python.org/mailman/listinfo/python-list


Re: Python3 change logs

2020-12-15 Thread Rich Shepard

On Tue, 15 Dec 2020, Skip Montanaro wrote:


Dang... I'm having very incomplete thoughts. Apologies for the multiple
replies when one would have sufficed.
https://docs.python.org/3/whatsnew/3.9.html


Skip,

No apologies needed. That page looks like a reformatted Release Notes.

Thanks again,

Rich
--
https://mail.python.org/mailman/listinfo/python-list


Re: dict.get(key, default) evaluates default even if key exists

2020-12-15 Thread Mark Polesky via Python-list
I see. Perhaps counterintuitive, but implemented consistently. Add it to the 
list of gotchas, I guess.

By the way... four helpful responses in under an hour, very impressive. Nice 
community here. Thanks to all who answered.

Mark






On Tuesday, December 15, 2020, 11:05:10 AM PST, Serhiy Storchaka 
 wrote: 





15.12.20 19:07, Mark Polesky via Python-list пише:

> # Running this script
> 
> D = {'a':1}
> def get_default():
>     print('Nobody expects this')
>     return 0
> print(D.get('a', get_default()))
> 
> # ...generates this output:
> 
> Nobody expects this
> 1
> 
> ###
> 
> Since I'm brand new to this community, I thought I'd ask here first... Is 
> this worthy of a bug report?  This behavior is definitely unexpected to me, 
> and I accidentally coded an endless loop in a mutual recursion situation 
> because of it.  Calling dict.get.__doc__ only gives this short sentence: 
> Return the value for key if key is in the dictionary, else default.  Nothing 
> in that docstring suggests that the default value is evaluated even if the 
> key exists, and I can't think of any good reason to do so.
> 
> Am I missing something?


You are missed that expressions for function arguments are always
evaluated before passing their values to a function. This is expected
behavior, and I can't remember any programming language in which it's
different.

So dict.get() returns the value of argument default, which is computed
by calling function get_default() before calling dict.get().

-- 
https://mail.python.org/mailman/listinfo/python-list

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: dict.get(key, default) evaluates default even if key exists

2020-12-15 Thread Grant Edwards
On 2020-12-15, Mark Polesky via Python-list  wrote:

> I see. Perhaps counterintuitive,

I guess that depends on what programming language you normally think
in. Python's handling of function parameters is exactly what I
expected, because all of the previous languages I used did the same
thing.

Purely out of curiosity, what language had you been using that behaved
otherwise?

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: dict.get(key, default) evaluates default even if key exists

2020-12-15 Thread Ethan Furman

On 12/15/20 9:07 AM, Mark Polesky via Python-list wrote:

> D = {'a':1}
>
> def get_default():
>  print('Nobody expects this')
>  return 0
>
> print(D.get('a', get_default()))

Python has short-circuiting logical operations, so one way to get the behavior 
you're looking for is:

D.get('a') or get_default()

--
~Ethan~
--
https://mail.python.org/mailman/listinfo/python-list


Re: dict.get(key, default) evaluates default even if key exists

2020-12-15 Thread Dan Stromberg
On Tue, Dec 15, 2020 at 11:05 AM Serhiy Storchaka 
wrote:

> 15.12.20 19:07, Mark Polesky via Python-list пише:
> > # Running this script
> >
> > D = {'a':1}
> > def get_default():
> > print('Nobody expects this')
> > return 0
> > print(D.get('a', get_default()))
> >
> > # ...generates this output:
> >
> > Nobody expects this
> > 1
> >
> > ###
> >
> > Since I'm brand new to this community, I thought I'd ask here first...
> Is this worthy of a bug report?  This behavior is definitely unexpected to
> me, and I accidentally coded an endless loop in a mutual recursion
> situation because of it.  Calling dict.get.__doc__ only gives this short
> sentence: Return the value for key if key is in the dictionary, else
> default.  Nothing in that docstring suggests that the default value is
> evaluated even if the key exists, and I can't think of any good reason to
> do so.
> >
> > Am I missing something?
>
> You are missed that expressions for function arguments are always
> evaluated before passing their values to a function. This is expected
> behavior, and I can't remember any programming language in which it's
> different.
>
I think Haskell might be different. It's a lazy language. So its '&&' and
'||' operators aren't specialcased by the language implementation to be
short-circuit - everything is just lazy naturally.  It's a neat idea, but
it's kind of hard to reason about its performance characteristics.  Python
has laziness in its 'and' and 'or', as well as in its generators - this
gives laziness where you tend to need it the most, without Python's
performance becoming hard to reason about (modulo the garbage collector).

One of the coolest things about Haskell is if you write a sort function in
it, then you can get a "give me the n lowest values" function for free.
That's lazy.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: dict.get(key, default) evaluates default even if key exists

2020-12-15 Thread dn via Python-list

> On Tue, Dec 15, 2020 at 9:57 AM Mark Polesky via Python-list <
> [email protected]> wrote:
>
>> Hi.
>>
>> # Running this script
>>
>> D = {'a':1}
>> def get_default():
>>  print('Nobody expects this')
>>  return 0
>> print(D.get('a', get_default()))
>>
>> # ...generates this output:
>>
>> Nobody expects this
>> 1
>>
>> ###
>>
>> Since I'm brand new to this community, I thought I'd ask here 
first... Is
>> this worthy of a bug report?  This behavior is definitely unexpected 
to me,

>> and I accidentally coded an endless loop in a mutual recursion situation
>> because of it.  Calling dict.get.__doc__ only gives this short sentence:
>> Return the value for key if key is in the dictionary, else default.
>> Nothing in that docstring suggests that the default value is 
evaluated even

>> if the key exists, and I can't think of any good reason to do so.


Hey this is fun! A quick search reveals that I've (mea culpa) always 
thought of dict.get() as providing a default *value* and not used a 
function in there to provide said value.


That said, the function's name says it all: get_default(). Is it 
'getting' a default value? No, it's (also) reporting-back. Thus a 
"side-effect". Undesirable, as you say.


Were it appropriate to report that a default value was necessary, maybe 
something like:


try:
print( d[ 'a' ] )
except KeyError:
print( "Nobody expects this" )
d[ 'a' ] = 0
--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: dict.get(key, default) evaluates default even if key exists

2020-12-15 Thread dn via Python-list

On 16/12/2020 07:52, Dan Stromberg wrote:
...> BTW, I tend to prefer collections.defaultdict over the two argument 
D.get

or setdefault.



Contrarily, dict.get() seems 'better', unless (a) the dict's values are 
all to be initialised to the same value, eg all None, int 0, or empty 
list []; or (b) my fingers will be tired by the number of dict.get() 
calls to be typed.


This thought partly because it may be some 'distance' between the 
definition of the 'dict' as a defaultdict cf the built-in 'original', 
and therefore a simple boy (like me) finds it easy to forget or 'lose 
track'.


Also, because it is unusual to come-across a default-factory which 
initialises values to the defaultdict other than uniformly.


Have you seen any application of defaultdict with some more-complex and 
cleverly-designed default-factory function?


Other than personal-preference (which should be respected), and a 
uniform default-value, what is the rationale for defaultdict over 
dict.get()?

--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: dict.get(key, default) evaluates default even if key exists

2020-12-15 Thread Chris Angelico
On Wed, Dec 16, 2020 at 10:03 AM dn via Python-list
 wrote:
>
> On 16/12/2020 07:52, Dan Stromberg wrote:
> ...> BTW, I tend to prefer collections.defaultdict over the two argument
> D.get
> > or setdefault.
>
>
> Contrarily, dict.get() seems 'better', unless (a) the dict's values are
> all to be initialised to the same value, eg all None, int 0, or empty
> list []; or (b) my fingers will be tired by the number of dict.get()
> calls to be typed.
>
> This thought partly because it may be some 'distance' between the
> definition of the 'dict' as a defaultdict cf the built-in 'original',
> and therefore a simple boy (like me) finds it easy to forget or 'lose
> track'.
>
> Also, because it is unusual to come-across a default-factory which
> initialises values to the defaultdict other than uniformly.
>
> Have you seen any application of defaultdict with some more-complex and
> cleverly-designed default-factory function?
>
> Other than personal-preference (which should be respected), and a
> uniform default-value, what is the rationale for defaultdict over
> dict.get()?

It depends on use-case. Using dict.get() is appropriate when you want
to know if something's there without prepopulating it; but if your
entire purpose is to then stash something into the dict, and you'll
ALWAYS be following the same pattern, then it's often more convenient
to use __missing__. And if your __missing__ method is, as it commonly
will be, constructing a brand new object, then it's easiest to use
defaultdict. But a defaultdict for integers might be better written as
a Counter instead. There are a lot of similar options, and you take
whatever's easiest for this particular job.

One VERY common use-case is gathering things together into lists based
on some sort of lookup key. This one is perfect for defaultdict:

messages = defaultdict(list)
for msg in get_messages():
messages[msg["author"]].append(msg)

That'll quickly and easily group the messages by their authors. The
first time an author is found, a new list is created, and then you
append them all.

(In digging for examples, I actually found a place where I'd used
defaultdict(collections.Counter) to create a nested structure very
easily. Worked out well. Pretty unusual thing to want though!)

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python3 change logs

2020-12-15 Thread Terry Reedy

On 12/15/2020 1:42 PM, Skip Montanaro wrote:

Dang... I'm having very incomplete thoughts. Apologies for the multiple
replies when one would have sufficed.

https://docs.python.org/3/whatsnew/3.9.html


In particular, for latest release (now 3.9) you would want tkinter in
https://docs.python.org/3/whatsnew/3.9.html#improved-modules
but nothing there.  However,
https://docs.python.org/3.8/whatsnew/3.8.html#tkinter

--
Terry Jan Reedy

--
https://mail.python.org/mailman/listinfo/python-list


Re: Library for text substitutions with calculations?

2020-12-15 Thread Terry Reedy

On 12/15/2020 11:25 AM, Bob Gailer wrote:

On Tue, Dec 15, 2020, 10:42 AM <[email protected]> wrote:


On 2020-12-15 at 16:04:55 +0100,
Jan Erik Moström  wrote:


I want to do some text substitutions but a bit more advanced than what
string.Template class can do. I addition to plain text substitution I

would

like to be able to do some calculations:

$value+1 - If value is 16 this would insert 17 in the text. I would also
like to subtract.


val = 2


print(f'{val+3}')

5


For more, see 
https://docs.python.org/3/reference/lexical_analysis.html#f-strings



--
Terry Jan Reedy


--
https://mail.python.org/mailman/listinfo/python-list


Re: dict.get(key, default) evaluates default even if key exists

2020-12-15 Thread 2QdxY4RzWzUUiLuE
On 2020-12-16 at 12:01:01 +1300,
dn via Python-list  wrote:

> > On Tue, Dec 15, 2020 at 9:57 AM Mark Polesky via Python-list <
> > [email protected]> wrote:
> >
> >> Hi.
> >>
> >> # Running this script
> >>
> >> D = {'a':1}
> >> def get_default():
> >>  print('Nobody expects this')
> >>  return 0
> >> print(D.get('a', get_default()))
> >>
> >> # ...generates this output:
> >>
> >> Nobody expects this
> >> 1
> >>
> >> ###
> >>
> >> Since I'm brand new to this community, I thought I'd ask here first... Is
> >> this worthy of a bug report?  This behavior is definitely unexpected to
> me,
> >> and I accidentally coded an endless loop in a mutual recursion situation
> >> because of it.  Calling dict.get.__doc__ only gives this short sentence:
> >> Return the value for key if key is in the dictionary, else default.
> >> Nothing in that docstring suggests that the default value is evaluated
> even
> >> if the key exists, and I can't think of any good reason to do so.
> 
> 
> Hey this is fun! A quick search reveals that I've (mea culpa) always thought
> of dict.get() as providing a default *value* and not used a function in
> there to provide said value.
> 
> That said, the function's name says it all: get_default(). Is it 'getting' a
> default value? No, it's (also) reporting-back. Thus a "side-effect".
> Undesirable, as you say.
> 
> Were it appropriate to report that a default value was necessary, maybe
> something like:
> 
> try:
> print( d[ 'a' ] )
> except KeyError:
> print( "Nobody expects this" )
> d[ 'a' ] = 0

Be careful:  that mutates d in the except clause, whereas calling
d.get('a', 0) doesn't, which may or may not be okay.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: dict.get(key, default) evaluates default even if key exists

2020-12-15 Thread Matt Ruffalo
On 15/12/20 15:26, Grant Edwards wrote:
> On 2020-12-15, Mark Polesky via Python-list  wrote:
>
>> I see. Perhaps counterintuitive,
> I guess that depends on what programming language you normally think
> in. Python's handling of function parameters is exactly what I
> expected, because all of the previous languages I used did the same
> thing.
>
> Purely out of curiosity, what language had you been using that behaved
> otherwise?
>

R comes to mind; arguments can even be defined as functions of other
arguments, and this is evaluated symbolically at call time:

"""
> f = function(x, y = 2 * x) { y }
> f(1)
[1] 2
> f(2)
[1] 4
> f(y = 3)
[1] 3
"""

MMR...
-- 
https://mail.python.org/mailman/listinfo/python-list