Re: Function to avoid a global variable

2020-04-28 Thread ast

Le 28/04/2020 à 08:51, ast a écrit :

Le 27/04/2020 à 04:46, Bob van der Poel a écrit :

Does this make as much sense as anything else? I need to track calls to a
function to make sure it doesn't get called to too great a depth. I had a
global which I inc/dec and then check in the function. Works fine, but 
I do

need to keep a global around just for this.

So ... instead I wrote a short function:

  def parseStack(inc, depth=[0]):
  if depth[0] > 50:
  ... report error and die nicely
 depth[0] += inc

This gets rid of the global, and it moves my error check out of the main
code as well. But, I never feel all that great about using a list in the
function call for static storage.




Using a callable object is the best way to define a function
with a memory

class ParseStack:
     def __init__(self):
     self.depth=0
     def __call__(self, inc, reset=True):
     if reset:
     self.depth = 0
     if self.depth > 50:
     ... report error
     self.depth += 1
     ... do your stuff

parse_stack = ParseStack()

and use "function" parse_stack

parse_stack(43)
...



def __call__(self, inc, reset=False):
--
https://mail.python.org/mailman/listinfo/python-list


Re: Function to avoid a global variable

2020-04-28 Thread Chris Angelico
On Tue, Apr 28, 2020 at 4:56 PM ast  wrote:
>
> Le 27/04/2020 à 04:46, Bob van der Poel a écrit :
> > Does this make as much sense as anything else? I need to track calls to a
> > function to make sure it doesn't get called to too great a depth. I had a
> > global which I inc/dec and then check in the function. Works fine, but I do
> > need to keep a global around just for this.
> >
> > So ... instead I wrote a short function:
> >
> >   def parseStack(inc, depth=[0]):
> >   if depth[0] > 50:
> >   ... report error and die nicely
> >  depth[0] += inc
> >
> > This gets rid of the global, and it moves my error check out of the main
> > code as well. But, I never feel all that great about using a list in the
> > function call for static storage.
> >
>
>
> Using a callable object is the best way to define a function
> with a memory
>
> class ParseStack:
>  def __init__(self):
>  self.depth=0
>  def __call__(self, inc, reset=True):
>  if reset:
>  self.depth = 0
>  if self.depth > 50:
>  ... report error
>  self.depth += 1
>  ... do your stuff
>
> parse_stack = ParseStack()
>
> and use "function" parse_stack
>
> parse_stack(43)

"Best"? Not sure about that. Functions are first-class objects in
Python, so a function *is* a callable object. You don't have to create
a custom class with a call method just to be able to attach attributes
to your function.

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


Re: Function to avoid a global variable

2020-04-28 Thread ast

Le 28/04/2020 à 09:13, Chris Angelico a écrit :

On Tue, Apr 28, 2020 at 4:56 PM ast  wrote:


Le 27/04/2020 à 04:46, Bob van der Poel a écrit :





"Best"? Not sure about that. Functions are first-class objects in
Python, so a function *is* a callable object. You don't have to create
a custom class with a call method just to be able to attach attributes
to your function.

ChrisA



Using a mutable object as a function default parameter value
and changing it inside the function looks like a "trick"
according to me.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Function to avoid a global variable

2020-04-28 Thread Chris Angelico
On Tue, Apr 28, 2020 at 5:26 PM ast  wrote:
>
> Le 28/04/2020 à 09:13, Chris Angelico a écrit :
> > On Tue, Apr 28, 2020 at 4:56 PM ast  wrote:
> >>
> >> Le 27/04/2020 à 04:46, Bob van der Poel a écrit :
>
>
> >
> > "Best"? Not sure about that. Functions are first-class objects in
> > Python, so a function *is* a callable object. You don't have to create
> > a custom class with a call method just to be able to attach attributes
> > to your function.
> >
> > ChrisA
> >
>
> Using a mutable object as a function default parameter value
> and changing it inside the function looks like a "trick"
> according to me.

Sure. But you're contrasting this to a suggestion to literally just
attach attributes to a function. Python lets you actually do that. You
don't have to simulate the feature by creating a custom class and
making it callable - you just straight-up add attributes to a
function. Sure, what you suggested works, but there's no reason to.

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


Re: Function to avoid a global variable

2020-04-28 Thread Antoon Pardon




Op 27/04/20 om 18:39 schreef Bob van der Poel:

Thanks Chris!

At least my code isn't (quite!) as bad as the xkcd example :)

Guess my "concern" is using the initialized array in the function:

def myfunct(a, b, c=array[0,1,2,3] )

always feels like an abuse.

Has anyone seriously considered implementing  a true static variable in a
function? Is there a PEP?


You can emulate a static variable is with a closure.

def make_parseStack():

depth = 0

def parseStack(inc):
   nonlocal depth

if depth > 50:
... report error and die nicely
depth += inc

return parseStack

parseStack = make_parseStack()

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


Re: Function to avoid a global variable

2020-04-28 Thread ast

Le 28/04/2020 à 09:52, ast a écrit :

Le 28/04/2020 à 09:39, Antoon Pardon a écrit :



Op 27/04/20 om 18:39 schreef Bob van der Poel:

Thanks Chris!

At least my code isn't (quite!) as bad as the xkcd example :)

Guess my "concern" is using the initialized array in the function:

    def myfunct(a, b, c=array[0,1,2,3] )

always feels like an abuse.

Has anyone seriously considered implementing  a true static variable 
in a

function? Is there a PEP?


You can emulate a static variable is with a closure.

def make_parseStack():

 depth = 0

 def parseStack(inc):
    nonlocal depth

 if depth > 50:
 ... report error and die nicely
 depth += inc

 return parseStack

parseStack = make_parseStack()



funny !

So we found 4 different ways to handle a memory in a function

1- Use a function parameter with a mutable default value

2- Use a function attribute

3- Use a callable object, and store your stuff inside an object attr

4- Use a closure to emulate a static function variable

Any more ?




5- Use a global variable, of course
--
https://mail.python.org/mailman/listinfo/python-list


Re: Function to avoid a global variable

2020-04-28 Thread ast

Le 28/04/2020 à 09:39, Antoon Pardon a écrit :



Op 27/04/20 om 18:39 schreef Bob van der Poel:

Thanks Chris!

At least my code isn't (quite!) as bad as the xkcd example :)

Guess my "concern" is using the initialized array in the function:

    def myfunct(a, b, c=array[0,1,2,3] )

always feels like an abuse.

Has anyone seriously considered implementing  a true static variable in a
function? Is there a PEP?


You can emulate a static variable is with a closure.

def make_parseStack():

     depth = 0

     def parseStack(inc):
    nonlocal depth

     if depth > 50:
     ... report error and die nicely
     depth += inc

     return parseStack

parseStack = make_parseStack()



funny !

So we found 4 different ways to handle a memory in a function

1- Use a function parameter with a mutable default value

2- Use a function attribute

3- Use a callable object, and store your stuff inside an object attr

4- Use a closure to emulate a static function variable

Any more ?


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


Re: Function to avoid a global variable

2020-04-28 Thread Christian Gollwitzer

Am 28.04.20 um 09:54 schrieb ast:

funny !

So we found 4 different ways to handle a memory in a function

1- Use a function parameter with a mutable default value

2- Use a function attribute

3- Use a callable object, and store your stuff inside an object attr

4- Use a closure to emulate a static function variable

Any more ?




5- Use a global variable, of course


That's definitely the least recommendable solution. Global variable 
names pollute the global namespace, therefore they don't make sense to 
just store state within one function. They should be reserved to the 
case where multiple functions access a common state. Usually it is best 
to restrict the scope of a variable to the region of code where it 
necessarily needs to be available.


Christian


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


Re: Conway's game of Life, just because.

2020-04-28 Thread ast

Le 07/05/2019 à 05:31, Paul Rubin a écrit :

#!/usr/bin/python3
from itertools import chain

def adjacents(cell):# generate coordinates of cell neighbors
 x, y = cell # a cell is just an x,y coordinate pair
 return ((x+i,y+j) for i in [-1,0,1] for j in [-1,0,1] if i or j)

def update(living): # living = currently living set of cells
 def ncount(cell):   # number of living neighbors of cell
 return sum(1 for c in adjacents(cell) if c in living)
 def uninhabitable(cell):# check if occupied cell should die
 return not(2 <= ncount(cell) <= 3)
 def fertile(cell):  # check if empty cell should have a birth
 return ncount(cell) == 3

 # get set of cells (living or not) that are adjacent to some living cell
 neighbors = set(chain.from_iterable(adjacents(c) for c in living))

 frontier = neighbors - living # the empty cells adjacent to living ones
 births = set(filter(fertile, frontier)) # are where births can happen
 deaths = set(filter(uninhabitable, living))
 return (living - deaths) | births

if __name__ == '__main__':
 r = set([(0,0),(0,1),(0,2),(1,2),(-1,1)])  # R-pentomino
 for i in range(1,1110):   # it should stabilize at generation 1104
 print (i,len(r))  # show generation number and population
 r = update(r)




I found in a Game Of Life program (not mine) a very clever method to
update a board of cell.

It worths seeing it.

X is a numpy 2D ndarray

def evolve(X):
''' Evolves a board of Game of Life for one turn '''
# Dead cells as a boundary condition
# Count neighbours
# Alive if 3 neighbours or 2 neighbours and already alive

Xi = X.astype(int)
neigh = np.zeros(Xi.shape)

neigh[1:-1,1:-1] = (Xi[:-2,:-2]  + Xi[:-2,1:-1] + Xi[:-2,2:] +
Xi[1:-1,:-2] +Xi[1:-1,2:]  +
Xi[2:,:-2]   + Xi[2:,1:-1]  + Xi[2:,2:])

return np.logical_or(neigh==3,np.logical_and(Xi==1,neigh==2))


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


Re: JH Conway memorial Life program

2020-04-28 Thread ast

Le 12/04/2020 à 23:40, Paul Rubin a écrit :

You might have heard by now that John Horton Conway died yesterday at
age 82, of complications from the SARS-Cov2 aka Corona virus.  Among his
many cool accomplishments was inventing the Game of Life, which was one
of my first exercises as a beginning programmer in middle school.  That
program used the naive approach of representing the game board as a 2-d
array and scanning all its cells at each generation.

Far better programmers and mathematicians than I am worked on
fantastically optimized Life programs and made wonderful discoveries
about Life patterns.  See https://conwaylife.com for a sample of that.

I never got too heavily into Life programming myself, but a year or two
ago I thought of a quite simple way to write a Life program whose
running time at each generation was linear in the number of active cells
(unlike my first program that I had written as a kid, whose running time
and space consumption was potentially unbounded even with a fixed
population).

In Conway's honor I'm appending the simple program (28 lines of Python)
below.

RIP, Prof. Conway.



#!/usr/bin/python3
from itertools import chain

def adjacents(cell):# generate coordinates of cell neighbors
 x, y = cell # a cell is just an x,y coordinate pair
 return ((x+i,y+j) for i in [-1,0,1] for j in [-1,0,1] if i or j)

def update(living): # living = currently living set of cells
 def ncount(cell):   # number of living neighbors of cell
 return sum(1 for c in adjacents(cell) if c in living)
 def uninhabitable(cell):# check if occupied cell should die
 return not(2 <= ncount(cell) <= 3)
 def fertile(cell):  # check if empty cell should have a birth
 return ncount(cell) == 3

 # get set of cells (living or not) that are adjacent to some living cell
 neighbors = set(chain.from_iterable(adjacents(c) for c in living))

 frontier = neighbors - living # the empty cells adjacent to living ones
 births = set(filter(fertile, frontier)) # are where births can happen
 deaths = set(filter(uninhabitable, living))
 return (living - deaths) | births

if __name__ == '__main__':
 r = set([(0,0),(0,1),(0,2),(1,2),(-1,1)])  # R-pentomino
 for i in range(1,1110):   # it should stabilize at generation 1104
 print (i,len(r))  # show generation number and population
 r = update(r)



I found in a Game Of Life program (not mine) a very clever method to
update a board of cell as a whole

It worths seeing it.

X is a numpy 2D ndarray

def evolve(X):
''' Evolves a board of Game of Life for one turn '''
# Dead cells as a boundary condition
# Count neighbours
# Alive if 3 neighbours or 2 neighbours and already alive

Xi = X.astype(int)
neigh = np.zeros(Xi.shape)

neigh[1:-1,1:-1] = (Xi[:-2,:-2]  + Xi[:-2,1:-1] + Xi[:-2,2:] +
Xi[1:-1,:-2] +Xi[1:-1,2:]  +
Xi[2:,:-2]   + Xi[2:,1:-1]  + Xi[2:,2:])

return np.logical_or(neigh==3,np.logical_and(Xi==1,neigh==2))
--
https://mail.python.org/mailman/listinfo/python-list


[RELEASE] Python 3.9.0a6 is now available for testing

2020-04-28 Thread Łukasz Langa
On behalf of the entire Python development community, and the currently serving 
Python release team in particular, I’m pleased to announce the release of 
Python 3.9.0a6. Get it here:

https://www.python.org/downloads/release/python-390a6/ 

This is an early developer preview of Python 3.9

Python 3.9 is still in development. This release, 3.9.0a6, is the last out of 
six planned alpha releases. Alpha releases are intended to make it easier to 
test the current state of new features and bug fixes and to test the release 
process. During the alpha phase, features may be added up until the start of 
the beta phase (2020-05-18) and, if necessary, may be modified or deleted up 
until the release candidate phase (2020-08-10). Please keep in mind that this 
is a preview release and its use is not recommended for production environments.

Major new features of the 3.9 series, compared to 3.8

Many new features for Python 3.9 are still being planned and written. Among the 
new major new features and changes so far:

PEP 584 , Union Operators in dict
PEP 585 , Type Hinting Generics In 
Standard Collections
PEP 593 , Flexible function and 
variable annotations
PEP 602 , Python adopts a stable 
annual release cadence
PEP 616 , String methods to remove 
prefixes and suffixes
PEP 617 , New PEG parser for CPython
BPO 38379 , garbage collection does not 
block on resurrected objects;
BPO 38692 , os.pidfd_open added that allows 
process management without races and signals;
BPO 39926 , Unicode support updated to 
version 13.0.0
BPO 1635741 , when Python is initialized 
multiple times in the same process, it does not leak memory anymore
A number of Python builtins (range, tuple, set, frozenset, list) are now sped 
up using PEP 590  vectorcall
A number of standard library modules (audioop, ast, grp, _hashlib, pwd, 
_posixsubprocess, random, select, struct, termios, zlib) are now using the 
stable ABI defined by PEP 384 .
(Hey, fellow core developer, if a feature you find important is missing from 
this list, let Łukasz know .)
The next pre-release, the first beta release of Python 3.9, will be 3.9.0b1. It 
is currently scheduled for 2020-05-18.

Your friendly release team,
Ned Deily @nad 
Steve Dower @steve.dower 
Łukasz Langa @ambv 
-- 
https://mail.python.org/mailman/listinfo/python-list


Bug in the urljoin library

2020-04-28 Thread Moro, Andrea via Python-list
Hello there,

I believe there is a bug in the urljoin library.

See below:

p = urlparse(url)
if p.scheme == '':
url = urljoin('http://', url)


Input:
domain.tld/somepath

Output
http:///domain.tld/somepath

p = urlparse(url)
if p.scheme == '':
url = urljoin('http:', url)

Input:
domain.tld/somepath

Output
http:///domain.tld/somepath

-- 

*Andrea Moro*
SEO Specialist – Digital Marketer

e: [email protected]
w: http://www.andreamoro.eu



Questo messaggio di posta elettronica può contenere informazioni riservate
o privilegi legali ed è destinato esclusivamente ad uso del destinatario.
Qualsiasi divulgazione non autorizzata, la diffusione, la distribuzione, la
copia o l'adozione di qualsiasi azione affidamento sulle informazioni in
esso contenute è vietata. Le e-mail non sono protette e non possono essere
garantite per essere esenti da errori in quanto possono essere
intercettate, modificate, o contenere virus. Si ritiene che chiunque
comunichi con il sottoscritto via e-mail abbia accettato questi rischi.
Andrea Moro non è responsabile per errori o omissioni in questo messaggio e
non assume alcuna responsabilità per eventuali danni derivanti
dall'utilizzo di e-mail. Qualsiasi opinione e di altre dichiarazioni
contenute nel presente messaggio ed eventuali allegati sono esclusivamente
quelle dell'autore e non rappresentano necessariamente quelli della società
menzionate o di altre persone eventualmente incluse nel presente messaggio.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Bug in the urljoin library

2020-04-28 Thread Peter Otten
Moro, Andrea via Python-list wrote:

> Hello there,
> 
> I believe there is a bug in the urljoin library.

I believe this is a case of garbage-in garbage-out ;)

Try

p = urlparse(url)
if not p.scheme:
url = urlunparse(p._replace(scheme="http"))

> 
> See below:
> 
> p = urlparse(url)
> if p.scheme == '':
> url = urljoin('http://', url)
> 
> 
> Input:
> domain.tld/somepath
> 
> Output
> http:///domain.tld/somepath
> 
> p = urlparse(url)
> if p.scheme == '':
> url = urljoin('http:', url)
> 
> Input:
> domain.tld/somepath
> 
> Output
> http:///domain.tld/somepath
> 


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


Fwd: Sorry, but . . .

2020-04-28 Thread Ganesha Sharma
-- Forwarded message -
From: Ganesha Sharma 
Date: Sat, Apr 18, 2020 at 8:00 AM
Subject: Sorry, but . . .
To: 


When I was installing Python 3.8.2, The installer gave me a BSoD. Is there
a way to fix that? I tried 3.6.2 but with Add to Path, with
environment variables off, it did not work. I just want the full Python,
but can you ask the developers to fix that in Python 3.9? That would be
great, or I just have to use repl.it to program. Python is my favorite
programming language and I love it.
I can't even use Pip! It's just adding python to the path manually is so
scary.

---
Tags: *BSoD, Add to path, Development, Online Platforms*
Sincerely, *Ganesha Sharma.*
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Fwd: Sorry, but . . .

2020-04-28 Thread Michael Torrie
On 4/28/20 2:41 PM, Ganesha Sharma wrote:
> When I was installing Python 3.8.2, The installer gave me a BSoD. Is there
> a way to fix that? I tried 3.6.2 but with Add to Path, with
> environment variables off, it did not work. I just want the full Python,
> but can you ask the developers to fix that in Python 3.9? That would be
> great, or I just have to use repl.it to program. Python is my favorite
> programming language and I love it.
> I can't even use Pip! It's just adding python to the path manually is so
> scary.

Sorry to hear you got a BSoD while running the installer. This is not a
usual occurrence, and is not generally happening to other users (on
Windows of course).  It's impossible to say what's causing this BSoD.
With modern versions of Windows, this is usually because of a hardware
fault or a bad driver.  There's really nothing Python developers can do
about this. This isn't a bug in the installer.  Rather the installer is
triggering something on your Windows system that isn't quite right.

You did not state where you got the installer from, or the operating
system version and hardware you were installing on.  Getting the
official installer from python.org is always recommended.  Have you
tried it on other machines?

When you say you tried 3.6.2 and it "did not work," what do you mean by
that?  Please describe the problem, and include copy and pasted error
messages (not screenshots) from the command prompt.

Glad you enjoy Python. Yes, it is a great language.

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