Re: Is that forwards first or backwards first? (Re: unintuitive for-loop behavior)

2016-10-03 Thread Gregory Ewing

On Mon, 3 Oct 2016 10:57:27 -0700 (PDT), sohcahto...@gmail.com declaimed
the following:

>

My car is similar, but the R is actually to the left of 1.  It looks like this:

R 1 3 5
+-+-+-+
2 4 6


Mine is actually like that too, but it feels like you're
doing the same thing in both cases -- push left as far
as it will go and then forward.

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


Re: PyQt5, OpenGL, where to start, minimal example code?

2016-10-03 Thread John Ladasky
On Monday, October 3, 2016 at 1:30:29 AM UTC-7, Phil Thompson wrote:
> On 3 Oct 2016, at 4:29 am, John Ladasky  wrote:

> > And as you can see: trying to call versionFunctions() is exactly where my 
> > program failed.
> 
> Try passing a QOpenGLVersionProfile object to versionFunctions() that has a 
> version set to one supported by PyQt.

Hi Phil,

I'm trying to follow your advice.  It's strange, "from PyQt5.QtGui import 
QOpenGLVersionProfile" works fine, and I can make an object of that type.

However: http://pyqt.sourceforge.net/Docs/PyQt5/ DOES NOT DOCUMENT 
QOpenGLVersionProfile.  I did find Qt documentation, at 
http://doc.qt.io/qt-5/qopenglversionprofile.html.  I will investigate this 
issue further.  Sometimes it isn't obvious how the C++ constructors are wrapped 
in Python.

If I ever understand a GUI like PyQt5 well enough, I'd like to contribute to 
its documentation.  Sigh.

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


Re: Is that forwards first or backwards first? (Re: unintuitive for-loop behavior)

2016-10-03 Thread Michael Torrie
On 10/03/2016 08:21 PM, Steve D'Aprano wrote:
> On Tue, 4 Oct 2016 05:48 am, Michael Torrie wrote:
> 
>> There is that old, but false, saying that the only intuitive interface
>> is the nipple.  Turns out everything, even that, is learned
> 
> Citation required.

Sure, just ask a nursing woman.

> Of course many things are intuitive/instinctive, e.g. breathing, but as far
> as *interfaces* go, I'd like to see the research that proves that babies
> don't intuitively know how to suckle from a nipple.

Research? Can't you just ask women about it?  I've heard quite a few
women (with experience) comment on the learned nature of babies nursing
over the years whenever this statement would come up in such company.
Which it will when you're in with a large group of married computer nerds.

Sucking seems to be instinctive but the actual interface is learned
(albeit very quickly) by experience.  Babies don't just see a nipple and
know what it's for. If your children ever did, they are remarkable
indeed.  Anyway, it's certainly not "intuitive" if intuitive is defined
as understanding with only basic perception of an object.  Similarly an
unmarked, red button you push to give you food is not intuitive.  You
can't see the button and know what it does without experience, or
someone telling you.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Assignment versus binding [was Re: unintuitive for-loop behavior]

2016-10-03 Thread Rustom Mody
On Tuesday, October 4, 2016 at 8:11:41 AM UTC+5:30, Steve D'Aprano wrote:
> On Mon, 3 Oct 2016 04:15 pm, Jussi Piitulainen wrote:
> 
> > Steve D'Aprano writes:
> >> Why shouldn't people say that binding and assignment are the same
> >> thing in Python? What's the difference?
> > 
> > Outside Python, (lambda x : f(x)) is said to "bind" x. It's different
> > from assigning a new value to x. It's similar to how quantifiers in
> > logic are said to bind their variables, so that variables bound to
> > different quantifiers are different variables.
> 
> o_O
> 
> Me: "How is binding different from assignment?"
> 
> You: "This is an example of binding: lambda x: f(x). Its different from
> assigning to x. Clear now?"
> 
> 
> What's "outside python"? Can you give some examples? Presumably you don't
> actually mean "every single programming language apart from Python", even
> if that's what it sounds like.
> 
> Anyway, I've done my own research, and what I've found is:
> 
> - Some people consider assignment and binding to be synonyms. This is
> especially common in OOP languages (like Python), and procedural languages.

Here’s C++
http://www.informit.com/articles/article.aspx?p=376876
roughly using initialization where Jussi/Greg/myself/etc are using binding



> 
> - Some people consider them to be different. This is especially common in
> functional languages with an academic emphasis.
> 
> For those who consider them different, the distinction is usually along
> these lines:
> 
> - Assignment associates a mutable label to a value. So if I say "x = 1",
> that sets up a labelled box and puts 1 inside that box. Then if I say "x =
> 2", the box is updated to contain 2 instead of 1.
> 
> - Binding is more like setting up a label or identifier for a constant. For
> example, in a legal contract, you might say words to the effect of:
> 
>John and Jane Smith, of 123 Evergreen Terrace, Metropolis ("the Client")
> 
> and then everywhere the contract refers to "the Client", you are supposed to
> mentally substitute "John and Jane Smith, of ...". Its a fixed label for a
> fixed value. Even if the value is mutable (John and Jane have a baby, and
> the baby is now automatically covered by the contract, the value cannot be
> replaced with a new value (you can't swap out John and Jane and replace
> them with their neighbours Fred and Ethel, you have to cancel the contract
> and write a new one).
> 
> So for these languages, bindings relate to a *fixed* association between a
> label and value. Whether the *value* itself is mutable or immutable, the
> association is fixed.

Are you suggesting that python can be understood without this distinction?
Consider the ‘mutable default gotcha’ in which the mutable is assigned but not 
mutated

tl;dr 
Many concepts are needed to understand programming languages
Some of them may be reified into the language; all cannot be.
“Not reified into the language” ≠ “Not a necessary concept for the language”
If you have variables+scopes you need (the concept of) binding
As understood by language-theorists, eg:
http://homepage.cs.uiowa.edu/~slonnegr/plf/Book/Chapter9.pdf
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: working with ctypes and complex data structures

2016-10-03 Thread eryk sun
On Mon, Oct 3, 2016 at 9:27 PM, Michael Felt  wrote:
>
> int perfstat_subsystem_total(
>perfstat_id_t *name,
>perfstat_subsystem_total_t *userbuff,
>int sizeof_struct,
>int desired_number);
> ...
>+79  class cpu_total:
>+80  def __init__(self):
>+81  __perfstat__ = CDLL("libperfstat.a(shr_64.o)")

Move loading the library and defining function prototypes to either
the module or class body. Also, don't use dunder names. The convention
for a private attribute is a single underscore. For type safety,
define each function's argtypes (and restype where required, the
default is c_int). For a more Pythonic interface, define a ctypes
errcheck function that encapsulates raising an appropriate exception
when a C call fails. For example:

import ctypes

# If the following types are used generally, define them at
# the module level, else define them in the class namespace
# that uses them.

perfstat = ctypes.CDLL("libperfstat.a(shr_64.o)")

class perfstat_id_t(ctypes.Structure):
pass

IDENTIFIER_LENGTH = 64

class time64_t(ctypes._SimpleCData):
_type_ = ctypes.c_int64._type_

time_t = time64_t

class perfstat_cpu_total_t(ctypes.Structure):
_fields_ = (("ncpus",   ctypes.c_int),
("ncpus_cfg",   ctypes.c_int),
("description", ctypes.c_char * IDENTIFIER_LENGTH),
("buffer1", ctypes.c_ulonglong * 15),
("lbolt",   time_t),
("loadavg", ctypes.c_ulonglong * 3),
("buffer2", ctypes.c_ulonglong * 29),
("ncpus_high",  ctypes.c_int),
("puser",   ctypes.c_ulonglong),
("psys",ctypes.c_ulonglong),
("pidle",   ctypes.c_ulonglong),
("pwait",   ctypes.c_ulonglong),
("buffer3", ctypes.c_ulonglong * 12))

def _perfstat_errcheck(result, func, args):
if result == -1:
# get error info and
raise SomeException()
return args

class CPUTotal(object):
# These may be defined here or just referenced here.
_perfstat = perfstat
_perfstat_id_t = perfstat_id_t
_perfstat_cpu_total_t = perfstat_cpu_total_t

_cpu_total = _perfstat.perfstat_cpu_total
_cpu_total.errcheck = _perfstat_errcheck
_cpu_total.argtypes = (
ctypes.POINTER(_perfstat_id_t),
ctypes.POINTER(_perfstat_cpu_total_t),
ctypes.c_int, ctypes.c_int)

def __init__(self):
self._tcpu = self._perfstat_cpu_total_t()
self._cpu_total(None,
ctypes.byref(self._tcpu),
ctypes.sizeof(self._tcpu), 1)
-- 
https://mail.python.org/mailman/listinfo/python-list


Assignment versus binding [was Re: unintuitive for-loop behavior]

2016-10-03 Thread Steve D'Aprano
On Mon, 3 Oct 2016 04:15 pm, Jussi Piitulainen wrote:

> Steve D'Aprano writes:
>> Why shouldn't people say that binding and assignment are the same
>> thing in Python? What's the difference?
> 
> Outside Python, (lambda x : f(x)) is said to "bind" x. It's different
> from assigning a new value to x. It's similar to how quantifiers in
> logic are said to bind their variables, so that variables bound to
> different quantifiers are different variables.

o_O

Me: "How is binding different from assignment?"

You: "This is an example of binding: lambda x: f(x). Its different from
assigning to x. Clear now?"


What's "outside python"? Can you give some examples? Presumably you don't
actually mean "every single programming language apart from Python", even
if that's what it sounds like.

Anyway, I've done my own research, and what I've found is:

- Some people consider assignment and binding to be synonyms. This is
especially common in OOP languages (like Python), and procedural languages.

- Some people consider them to be different. This is especially common in
functional languages with an academic emphasis.

For those who consider them different, the distinction is usually along
these lines:

- Assignment associates a mutable label to a value. So if I say "x = 1",
that sets up a labelled box and puts 1 inside that box. Then if I say "x =
2", the box is updated to contain 2 instead of 1.

- Binding is more like setting up a label or identifier for a constant. For
example, in a legal contract, you might say words to the effect of:

   John and Jane Smith, of 123 Evergreen Terrace, Metropolis ("the Client")

and then everywhere the contract refers to "the Client", you are supposed to
mentally substitute "John and Jane Smith, of ...". Its a fixed label for a
fixed value. Even if the value is mutable (John and Jane have a baby, and
the baby is now automatically covered by the contract, the value cannot be
replaced with a new value (you can't swap out John and Jane and replace
them with their neighbours Fred and Ethel, you have to cancel the contract
and write a new one).

So for these languages, bindings relate to a *fixed* association between a
label and value. Whether the *value* itself is mutable or immutable, the
association is fixed.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Is that forwards first or backwards first? (Re: unintuitive for-loop behavior)

2016-10-03 Thread Steve D'Aprano
On Tue, 4 Oct 2016 05:48 am, Michael Torrie wrote:

> There is that old, but false, saying that the only intuitive interface
> is the nipple.  Turns out everything, even that, is learned

Citation required.

Of course many things are intuitive/instinctive, e.g. breathing, but as far
as *interfaces* go, I'd like to see the research that proves that babies
don't intuitively know how to suckle from a nipple.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Is that forwards first or backwards first? (Re: unintuitive for-loop behavior)

2016-10-03 Thread Gregory Ewing

BartC wrote:

On 03/10/2016 12:53, Marko Rauhamaa wrote:


Well, it could be worse. This layout is pretty traditional:

1  3  5
|  |  |
+--+--+
|  |  |
2  4  R


Yes, you get a funny grinding sound when attempting to change from 5th 
to '6th' at 70mph/110kph. Fortunately it doesn't actually go into reverse.


Yes, my previous car had that layout. I never actually
tried to go from 5 to R at speed, so I don't know
what it would have sounded like, but I know from the
service manual that it had a mechanism to prevent it
from happening.

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


Re: Create a map for data to flow through

2016-10-03 Thread Gregory Ewing

Sayth Renshaw wrote:

Is there a standard library feature that allows you to define a declarative
map or statement that defines the data and its objects to be parsed and
output format?


Not really.


Just wondering as for loops are good but when i end up 3-4 for loops deep and
want multiple matches at each level i am finding it harder to manage.


When your loops get more than about one or two levels deep,
think about separaring each level into its own function.
That will allow you to think about just one part of the
problem at a time, and help you to not get confused.

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


Re: working with ctypes and complex data structures

2016-10-03 Thread Michael Felt



On 02-Oct-16 19:50, Michael Felt wrote:

class perfstat_cpu_total_t(Structure):
"""
typedef struct { /* global cpu information */
int ncpus;/* number of active logical 
processors */

int ncpus_cfg; /* number of configured processors */
char description[IDENTIFIER_LENGTH]; /* processor description 
(type/official name) */
u_longlong_t buffer1[15];   /*  several variables being 
skipped for now */
time_t lbolt;  /* number of ticks since last 
reboot */
u_longlong_t loadavg[3];  /* (1

Re: Is that forwards first or backwards first? (Re: unintuitive for-loop behavior)

2016-10-03 Thread Michael Torrie
On 10/03/2016 11:57 AM, sohcahto...@gmail.com wrote:
> Surprisingly, despite driving that previous car for 13 years, the switch was 
> incredibly easy.  I've never accidentally gone to sixth gear instead of 
> reverse, or forgotten to shift into sixth on the highway.  Also, accidentally 
> going into first when I want to reverse has never happened.  I was actually 
> pretty surprised.  I thought I'd mess it up constantly for the first couple 
> months.

I drive a lot of trucks with different patterns.  One is the traditional
one with reverse to the right and back.  Several use left and up for
reverse (first or low is left and down). Never had bothered me and I
rarely select reverse when I want forward or vice versa.  In fact all it
takes to determine which pattern I have without looking is to see which
side of the H has the spring-back on it.

What would throw me off would be left-side driving where the pattern is
the same but the stick is on the left hand side of me and the pattern
works its way towards me instead of away.

There is that old, but false, saying that the only intuitive interface
is the nipple.  Turns out everything, even that, is learned, and humans
are pretty adaptable, even to non-obvious and non-intuitive things such
as how python's loops work, lambdas, comprehensions, etc.  Anyone ever
driven a 5 and 4 transmission? :)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is that forwards first or backwards first? (Re: unintuitive for-loop behavior)

2016-10-03 Thread Michael Torrie
On 10/03/2016 03:10 AM, Gregory Ewing wrote:
> Rustom Mody wrote:
>> My new car goes in reverse when I put it in first gear but only on full-moon 
>> nights with the tank on reserve when the left light is blinking
> 
> OT aside: When I went to take my current car (a manual)
> for a test drive, I had to stop and ask the dealer how
> to put it into reverse.
> 
> Turns out the only difference between first and reverse
> on that model is whether you lift up a little ring on the
> shaft of the gear lever prior to engagement.
> 
> Who came up with *that* brilliant piece of user interface
> design I don't know. It seems specifically designed to
> encourage velocity sign errors when starting off...

Yeah I'm not sure what's up with car engineers these days. The Chrysler
transmission shifter that springs back to the center position is another
one of those brain-dead things.  There's no way to know if you've made
it all the way into park without looking at the dash.  Click it up and
hold it to hit neutral, then reverse, then park.  Then it springs back
to center position.  This contributed to the death of that Star Trek
movie actor.  He thought it was in park but it wasn't, and it rolled
over him.


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


Re: working with ctypes and complex data structures

2016-10-03 Thread Michael Felt



On 03-Oct-16 16:35, Michael Felt wrote:

I'd alias the type instead of defining a struct, e.g. `time_t =
c_long`. This preserves automatic conversion of the simple type.
The reason for the not using alias is because a) I was trying to be 
more inline with the text of the include file.
I will have to check the sizeof c_long (i.e., sizeof(long) in both 32 
and 64-bit modes

Also, sys.maxsize is based on the platform's size_t type. That's
generally the same size as a pointer, but C doesn't require this.
Instead use sizeof(c_void_p), which will be 8 on a 64-bit platform and
4 on a 32-bit platform. 


I had checked this before - I shall have to try a 32-bit python to see 
what _ctypes is doing with c_long on AIX - is it 4, or is it 8.
michael@x071:[/data/prj/python/cloud-init/aix-cloud-init-0.7.8.1/new]cat 
xxx.c

#include 
time_t
lbolt()
{
perfstat_cpu_total_t cpu_totals;
void *p1, *p2;

printf("int_size:%d\n", sizeof(int));
printf("long_size:%d\n", sizeof(long));
printf("timet_size:%d\n", sizeof(time_t));
printf("void_ptr_size:%d\n", sizeof(void *));
printf("lbolt_size:%d\n", sizeof(cpu_totals.lbolt));

p1 = &cpu_totals;
p2 = &cpu_totals.lbolt;
printf("lbolt offset:%d\n", p2 - p1);
}

main()
{
lbolt();
}

michael@x071:[/data/prj/python/cloud-init/aix-cloud-init-0.7.8.1/new]cc 
-q32 >

int_size:4
long_size:4
timet_size:4
void_ptr_size:4
lbolt_size:4
lbolt offset:192
michael@x071:[/data/prj/python/cloud-init/aix-cloud-init-0.7.8.1/new]cc 
-q64 >

int_size:4
long_size:8
timet_size:8
void_ptr_size:8
lbolt_size:8
lbolt offset:192


I think 4 and 8 because of problems I have with this block when not in 
the right "mode", i.e. SIZEOF_LONG changes


#if LONG_BIT != 8 * SIZEOF_LONG
/* 04-Oct-2000 LONG_BIT is apparently (mis)defined as 64 on some recent
 * 32-bit platforms using gcc.  We try to catch that here at compile-time
 * rather than waiting for integer multiplication to trigger bogus
 * overflows.
 */
#error "LONG_BIT definition appears wrong for platform (bad gcc/glibc 
config?)."

#endif

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


Re: python (scipy) TypeError

2016-10-03 Thread chrischris201444
Τη Δευτέρα, 3 Οκτωβρίου 2016 - 7:17:03 μ.μ. UTC+3, ο χρήστης 
chrischr...@gmail.com έγραψε:
> hello
> 
> 
> i try to follow some tutorial but i have that error :
> 
> Traceback (most recent call last):
>   File "C:\Python27\test\test\earth.py", line 42, in 
> slope_array = np.ones_like(data_array) * nodataval
> TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
> 
> 
> first i define that lines of code :
> 
> data_array = raster2array(filename)
> nodataval = getNoDataValue(filename)
> 
> and the line with error :
> 
> slope_array = np.ones_like(data_array) * nodataval
> 
> how can i fix this error ?i change type field ?
> 
> on the four prints:
> 
> print(resolution)
> print(nodataval)
> print(type(data_array))
> print(data_array.shape)
> 
> i take that exports :
> 
> {'east-west': 0.0002778, 'north-south': 0.0002778}
> None
> 
> (3601, 3601)
> 
> the full code :
> 
> 
> from __future__ import division
> from osgeo import gdal
> from matplotlib.colors import ListedColormap
> from matplotlib import colors
> import sys
> import numpy as np
> import matplotlib
> import matplotlib.pyplot as plt
> import math
> 
> filename = 'dem.tif'
> 
> def getResolution(rasterfn):
> raster = gdal.Open(rasterfn)
> geotransform = raster.GetGeoTransform()
> res = {"east-west": abs(geotransform[1]), 
>"north-south": abs(geotransform[5])}
> return res
> 
> def raster2array(rasterfn):
> raster = gdal.Open(rasterfn)
> band = raster.GetRasterBand(1)
> return band.ReadAsArray()
> 
> def getNoDataValue(rasterfn):
> raster = gdal.Open(rasterfn)
> band = raster.GetRasterBand(1)
> return band.GetNoDataValue()
> 
> data_array = raster2array(filename)
> nodataval = getNoDataValue(filename)
> resolution = getResolution(filename)
> print(resolution)
> print(nodataval)
> 
> print(type(data_array))
> print(data_array.shape)
> 
> num_rows = data_array.shape[0]
> num_cols = data_array.shape[1]
> 
> slope_array = np.ones_like(data_array) * nodataval
> aspect_array = np.ones_like(data_array) * nodataval
> 
> for i in range(1, num_rows - 1):
> for j in range(1, num_cols - 1):
> a = data_array[i - 1][j - 1]
> b = data_array[i - 1][j]
> c = data_array[i - 1][j + 1]
> d = data_array[i][j - 1]
> e = data_array[i][j]
> f = data_array[i][j + 1]
> g = data_array[i + 1][j - 1]
> h = data_array[i + 1][j]
> q = data_array[i + 1][j + 1]
> 
> vals = [a, b, c, d, e, f, g, h, q]
> 
> if nodataval in vals:
> all_present = False
> else:
> all_present = True
> 
> if all_present == True:
> dz_dx = (c + (2 * f) + q - a - (2 * d) - g) / (8 * 
> resolution['east-west'])
> dz_dy = (g + (2 * h) + q - a - (2 * b) - c) / (8 * 
> resolution['north-south'])
> dz_dx_sq = math.pow(dz_dx, 2)
> dz_dy_sq = math.pow(dz_dy, 2)
> 
> rise_run = math.sqrt(dz_dx_sq + dz_dy_sq)
> slope_array[i][j] = math.atan(rise_run) * 57.29578
> 
> aspect = math.atan2(dz_dy, (-1 * dz_dx)) * 57.29578
> if aspect < 0:
> aspect_array[i][j] = 90 - aspect
> elif aspect > 90:
> aspect_array[i][j] = 360 - aspect + 90
> else:
> aspect_array[i][j] = 90 - aspect
> 
> hist, bins = np.histogram(slope_array, bins=100, range=(0, 
> np.amax(slope_array)))
> width = 0.7 * (bins[1] - bins[0])
> center = (bins[:-1] + bins[1:]) / 2
> plt.bar(center, hist, align='center', width=width)
> plt.xlabel('Slope (degrees)')
> plt.ylabel('Frequency')
> plt.show()
> 
> color_map = ListedColormap(['white', 'darkgreen', 'green', 'limegreen', 
> 'lime', 
> 'greenyellow', 'yellow', 'gold', 
> 'orange', 'orangered', 'red'])
> 
> # range begins at negative value so that missing values are white
> color_bounds = list(range(-3, math.ceil(np.amax(slope_array)), 1))
> color_norm = colors.BoundaryNorm(color_bounds, color_map.N)
> 
> #Create the plot and colorbar
> img = plt.imshow(slope_array, cmap = color_map, norm = color_norm)
> cbar = plt.colorbar(img, cmap = color_map, norm = color_norm,
>boundaries = color_bounds, ticks = color_bounds)
> 
> #Show the visualization
> plt.axis('off')
> plt.title("Slope (degrees)")
> plt.show()
> plt.close()

yes you are corrent now i dont have error,i have coloring from -3 to 50 with 
step 1.. the -3 number is the -3 from my range ?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is that forwards first or backwards first? (Re: unintuitive for-loop behavior)

2016-10-03 Thread sohcahtoa82
On Monday, October 3, 2016 at 2:11:12 AM UTC-7, Gregory Ewing wrote:
> Rustom Mody wrote:
> > My new car goes in reverse when I put it in first gear but only on 
> > full-moon 
> > nights with the tank on reserve when the left light is blinking
> 
> OT aside: When I went to take my current car (a manual)
> for a test drive, I had to stop and ask the dealer how
> to put it into reverse.
> 
> Turns out the only difference between first and reverse
> on that model is whether you lift up a little ring on the
> shaft of the gear lever prior to engagement.
> 
> Who came up with *that* brilliant piece of user interface
> design I don't know. It seems specifically designed to
> encourage velocity sign errors when starting off...
> 
> -- 
> Greg

My car is similar, but the R is actually to the left of 1.  It looks like this:

R 1 3 5
+-+-+-+
  2 4 6

However, you can't get to R unless you lift the ring around the stick upwards.  
once you go to the far left, the ring stays up until you slide it out of the 
far left notch.  My previous car was the traditional:

1 3 5
+-+-+
2 4 R

Surprisingly, despite driving that previous car for 13 years, the switch was 
incredibly easy.  I've never accidentally gone to sixth gear instead of 
reverse, or forgotten to shift into sixth on the highway.  Also, accidentally 
going into first when I want to reverse has never happened.  I was actually 
pretty surprised.  I thought I'd mess it up constantly for the first couple 
months.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python (scipy) TypeError

2016-10-03 Thread MRAB

On 2016-10-03 17:48, chrischris201...@gmail.com wrote:

Τη Δευτέρα, 3 Οκτωβρίου 2016 - 7:17:03 μ.μ. UTC+3, ο χρήστης 
chrischr...@gmail.com έγραψε:

hello


i try to follow some tutorial but i have that error :

Traceback (most recent call last):
  File "C:\Python27\test\test\earth.py", line 42, in 
slope_array = np.ones_like(data_array) * nodataval
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'


[snip]


#Show the visualization
plt.axis('off')
plt.title("Slope (degrees)")
plt.show()
plt.close()

yes you are correct i solution this error but now i have another error in the 
line :color_bounds = list(range(-3, math.ceil(np.amax(slope_array)), 1))

error massage :
Traceback (most recent call last):
  File "C:\Python27\test\test\earth.py", line 95, in 
color_bounds = list(range(-3, math.ceil(np.amax(slope_array)), 1))
TypeError: range() integer end argument expected, got float.


any idea ?


Look at the help for math.ceil:

>>> help(math.ceil)
Help on built-in function ceil in module math:

"""
ceil(...)
ceil(x)

Return the ceiling of x as a float.
This is the smallest integral value >= x.
"""

It returns an integer value, but as a _float_.

'range' expects an int, not a float, so you'll need to convert the float 
to an int:


color_bounds = list(range(-3, int(math.ceil(np.amax(slope_array))), 1))


Did you copy the code straight from the tutorial?

You're using Python 2.7, but for which version of Python was the 
tutorial written? Python 2 or Python 3?


If it was written for Python 3 and you're using Python 2, that might 
explain why the code isn't working for you. (In Python 2, math.ceil 
returns a float, whereas in Python 3 it returns an int.)


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


Re: Copying a compiled Python from one system to another

2016-10-03 Thread Paul Rubin
Steve D'Aprano  writes:
> The dependencies needed to build 4.8 aren't available for my system. And
> there's no supported upgrade path.

If you're system runs 4.4 it should be able to build 4.8 I'd hope.  I
have Debian 7 which comes with 4.7, and I was able to download and build
6.1 with any significant trouble.  I had to change the library path to
build stuff with 6.1 and a locally installed library.  What system are
you running?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: print to previous line in console

2016-10-03 Thread Adam M
On Monday, October 3, 2016 at 12:46:41 PM UTC-4, Skip Montanaro wrote:
> On Mon, Oct 3, 2016 at 10:23 AM, udhay prakash pethakamsetty
> > Hi skip,
> >
> > I am unable to even install that curses package
> >
> >
> > C:\>pip install curses
> > Collecting curses
> >   Could not find a version that satisfies the requirement curses (from
> > versions: )
> > No matching distribution found for curses
> >
> >
> > I am using python 2.7.
> 
> You shouldn't have to install it. Unless your Python installation is
> defective in some regard, you should have it. That said, I don't do
> Windows, so perhaps curses isn't available there.
> 
> % python
> Python 2.7.2 (default, Nov 14 2012, 05:07:35)
> [GCC 4.4.6 [TWW]] on linux3
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import curses
> >>> curses.version
> '2.2'
> 
> Oh, and when asking for help, it's best to cc the mailing list, not
> just the person to whom you are responding. You get more timely -- and
> more complete -- help. In this case, I can't state authoritatively if
> curses is available on Windows. You also don't know that I didn't hit
> "send" on my original response then immediately head off to the North
> Woods for a week of hiking.
> 
> Skip

Because on Linux it is part of 2.7.x distribution. On Windows it is not.
You will need to download wheel from that place:
http://www.lfd.uci.edu/~gohlke/pythonlibs/
And install it using PIP.

Regards
Adam

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


Re: Is that forwards first or backwards first? (Re: unintuitive for-loop behavior)

2016-10-03 Thread breamoreboy
On Monday, October 3, 2016 at 5:41:23 PM UTC+1, BartC wrote:
> On 03/10/2016 16:03, wrote:
> > On Monday, October 3, 2016 at 12:53:55 PM UTC+1, Marko Rauhamaa wrote:
> >> Gregory Ewing:
> >>
> >>> Turns out the only difference between first and reverse on that model
> >>> is whether you lift up a little ring on the shaft of the gear lever
> >>> prior to engagement.
> >>>
> >>> Who came up with *that* brilliant piece of user interface design I
> >>> don't know. It seems specifically designed to encourage velocity sign
> >>> errors when starting off...
> >>
> >> Well, it could be worse. This layout is pretty traditional:
> >>
> >> 1  3  5
> >> |  |  |
> >> +--+--+
> >> |  |  |
> >> 2  4  R
> 
> >
> > There was the shift on the steering column on the 2CV, but then there's 
> > also this.
> >
> > 
> > Traditional Italian military vehicle layout.
> >
> >  1  3  5
> >  |  |  |
> >  +--+--+
> >  |  |  |
> >  2  4  F
> >
> > 
> 
> I don't get it. Shouldn't it be:
> 
>R  R  R
>|  |  |
>+--+--+
>|  |  |
>R  R  R
> 
> ?
> 
> -- 
> Bartc
> 
> (It's OK, I'm Italian...)

A very poor design, what happens if the enemy attack from the rear? :)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python (scipy) TypeError

2016-10-03 Thread chrischris201444
Τη Δευτέρα, 3 Οκτωβρίου 2016 - 7:17:03 μ.μ. UTC+3, ο χρήστης 
chrischr...@gmail.com έγραψε:
> hello
> 
> 
> i try to follow some tutorial but i have that error :
> 
> Traceback (most recent call last):
>   File "C:\Python27\test\test\earth.py", line 42, in 
> slope_array = np.ones_like(data_array) * nodataval
> TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
> 
> 
> first i define that lines of code :
> 
> data_array = raster2array(filename)
> nodataval = getNoDataValue(filename)
> 
> and the line with error :
> 
> slope_array = np.ones_like(data_array) * nodataval
> 
> how can i fix this error ?i change type field ?
> 
> on the four prints:
> 
> print(resolution)
> print(nodataval)
> print(type(data_array))
> print(data_array.shape)
> 
> i take that exports :
> 
> {'east-west': 0.0002778, 'north-south': 0.0002778}
> None
> 
> (3601, 3601)
> 
> the full code :
> 
> 
> from __future__ import division
> from osgeo import gdal
> from matplotlib.colors import ListedColormap
> from matplotlib import colors
> import sys
> import numpy as np
> import matplotlib
> import matplotlib.pyplot as plt
> import math
> 
> filename = 'dem.tif'
> 
> def getResolution(rasterfn):
> raster = gdal.Open(rasterfn)
> geotransform = raster.GetGeoTransform()
> res = {"east-west": abs(geotransform[1]), 
>"north-south": abs(geotransform[5])}
> return res
> 
> def raster2array(rasterfn):
> raster = gdal.Open(rasterfn)
> band = raster.GetRasterBand(1)
> return band.ReadAsArray()
> 
> def getNoDataValue(rasterfn):
> raster = gdal.Open(rasterfn)
> band = raster.GetRasterBand(1)
> return band.GetNoDataValue()
> 
> data_array = raster2array(filename)
> nodataval = getNoDataValue(filename)
> resolution = getResolution(filename)
> print(resolution)
> print(nodataval)
> 
> print(type(data_array))
> print(data_array.shape)
> 
> num_rows = data_array.shape[0]
> num_cols = data_array.shape[1]
> 
> slope_array = np.ones_like(data_array) * nodataval
> aspect_array = np.ones_like(data_array) * nodataval
> 
> for i in range(1, num_rows - 1):
> for j in range(1, num_cols - 1):
> a = data_array[i - 1][j - 1]
> b = data_array[i - 1][j]
> c = data_array[i - 1][j + 1]
> d = data_array[i][j - 1]
> e = data_array[i][j]
> f = data_array[i][j + 1]
> g = data_array[i + 1][j - 1]
> h = data_array[i + 1][j]
> q = data_array[i + 1][j + 1]
> 
> vals = [a, b, c, d, e, f, g, h, q]
> 
> if nodataval in vals:
> all_present = False
> else:
> all_present = True
> 
> if all_present == True:
> dz_dx = (c + (2 * f) + q - a - (2 * d) - g) / (8 * 
> resolution['east-west'])
> dz_dy = (g + (2 * h) + q - a - (2 * b) - c) / (8 * 
> resolution['north-south'])
> dz_dx_sq = math.pow(dz_dx, 2)
> dz_dy_sq = math.pow(dz_dy, 2)
> 
> rise_run = math.sqrt(dz_dx_sq + dz_dy_sq)
> slope_array[i][j] = math.atan(rise_run) * 57.29578
> 
> aspect = math.atan2(dz_dy, (-1 * dz_dx)) * 57.29578
> if aspect < 0:
> aspect_array[i][j] = 90 - aspect
> elif aspect > 90:
> aspect_array[i][j] = 360 - aspect + 90
> else:
> aspect_array[i][j] = 90 - aspect
> 
> hist, bins = np.histogram(slope_array, bins=100, range=(0, 
> np.amax(slope_array)))
> width = 0.7 * (bins[1] - bins[0])
> center = (bins[:-1] + bins[1:]) / 2
> plt.bar(center, hist, align='center', width=width)
> plt.xlabel('Slope (degrees)')
> plt.ylabel('Frequency')
> plt.show()
> 
> color_map = ListedColormap(['white', 'darkgreen', 'green', 'limegreen', 
> 'lime', 
> 'greenyellow', 'yellow', 'gold', 
> 'orange', 'orangered', 'red'])
> 
> # range begins at negative value so that missing values are white
> color_bounds = list(range(-3, math.ceil(np.amax(slope_array)), 1))
> color_norm = colors.BoundaryNorm(color_bounds, color_map.N)
> 
> #Create the plot and colorbar
> img = plt.imshow(slope_array, cmap = color_map, norm = color_norm)
> cbar = plt.colorbar(img, cmap = color_map, norm = color_norm,
>boundaries = color_bounds, ticks = color_bounds)
> 
> #Show the visualization
> plt.axis('off')
> plt.title("Slope (degrees)")
> plt.show()
> plt.close()
yes you are correct i solution this error but now i have another error in the 
line :color_bounds = list(range(-3, math.ceil(np.amax(slope_array)), 1))

error massage :
Traceback (most recent call last):
  File "C:\Python27\test\test\earth.py", line 95, in 
color_bounds = list(range(-3, math.ceil(np.amax(slope_array)), 1))
TypeError: range() integer end argument expected, got float.


any idea ?

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


Re: python (scipy) TypeError

2016-10-03 Thread MRAB

On 2016-10-03 17:14, chrischris201...@gmail.com wrote:

hello


i try to follow some tutorial but i have that error :

Traceback (most recent call last):
  File "C:\Python27\test\test\earth.py", line 42, in 
slope_array = np.ones_like(data_array) * nodataval
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'


The errors is saying that nodataval is None.



first i define that lines of code :

data_array = raster2array(filename)
nodataval = getNoDataValue(filename)

and the line with error :

slope_array = np.ones_like(data_array) * nodataval

how can i fix this error ?i change type field ?

on the four prints:


Look at what print(nodataval) shows. It says that nodataval is None.


print(resolution)
print(nodataval)
print(type(data_array))
print(data_array.shape)

i take that exports :

{'east-west': 0.0002778, 'north-south': 0.0002778}
None

(3601, 3601)

the full code :

Why is nodataval None? It's because getNoDataValue returned None, which 
means that band.GetNoDataValue() returned None.


You'll have to read the docs to see under what conditions it does that.



from __future__ import division
from osgeo import gdal
from matplotlib.colors import ListedColormap
from matplotlib import colors
import sys
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import math

filename = 'dem.tif'

def getResolution(rasterfn):
raster = gdal.Open(rasterfn)
geotransform = raster.GetGeoTransform()
res = {"east-west": abs(geotransform[1]),
   "north-south": abs(geotransform[5])}
return res

def raster2array(rasterfn):
raster = gdal.Open(rasterfn)
band = raster.GetRasterBand(1)
return band.ReadAsArray()

def getNoDataValue(rasterfn):
raster = gdal.Open(rasterfn)
band = raster.GetRasterBand(1)
return band.GetNoDataValue()

data_array = raster2array(filename)
nodataval = getNoDataValue(filename)
resolution = getResolution(filename)
print(resolution)
print(nodataval)

print(type(data_array))
print(data_array.shape)


[snip]

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


Re: print to previous line in console

2016-10-03 Thread Skip Montanaro
On Mon, Oct 3, 2016 at 10:23 AM, udhay prakash pethakamsetty
 wrote:
> Hi skip,
>
> I am unable to even install that curses package
>
>
> C:\>pip install curses
> Collecting curses
>   Could not find a version that satisfies the requirement curses (from
> versions: )
> No matching distribution found for curses
>
>
> I am using python 2.7.

You shouldn't have to install it. Unless your Python installation is
defective in some regard, you should have it. That said, I don't do
Windows, so perhaps curses isn't available there.

% python
Python 2.7.2 (default, Nov 14 2012, 05:07:35)
[GCC 4.4.6 [TWW]] on linux3
Type "help", "copyright", "credits" or "license" for more information.
>>> import curses
>>> curses.version
'2.2'

Oh, and when asking for help, it's best to cc the mailing list, not
just the person to whom you are responding. You get more timely -- and
more complete -- help. In this case, I can't state authoritatively if
curses is available on Windows. You also don't know that I didn't hit
"send" on my original response then immediately head off to the North
Woods for a week of hiking.

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


Re: Is that forwards first or backwards first? (Re: unintuitive for-loop behavior)

2016-10-03 Thread BartC

On 03/10/2016 16:03, breamore...@gmail.com wrote:

On Monday, October 3, 2016 at 12:53:55 PM UTC+1, Marko Rauhamaa wrote:

Gregory Ewing:


Turns out the only difference between first and reverse on that model
is whether you lift up a little ring on the shaft of the gear lever
prior to engagement.

Who came up with *that* brilliant piece of user interface design I
don't know. It seems specifically designed to encourage velocity sign
errors when starting off...


Well, it could be worse. This layout is pretty traditional:

1  3  5
|  |  |
+--+--+
|  |  |
2  4  R




There was the shift on the steering column on the 2CV, but then there's also 
this.


Traditional Italian military vehicle layout.

 1  3  5
 |  |  |
 +--+--+
 |  |  |
 2  4  F




I don't get it. Shouldn't it be:

  R  R  R
  |  |  |
  +--+--+
  |  |  |
  R  R  R

?

--
Bartc

(It's OK, I'm Italian...)
--
https://mail.python.org/mailman/listinfo/python-list


Re: python (scipy) TypeError

2016-10-03 Thread Peter Pearson
On Mon, 3 Oct 2016 09:14:23 -0700 (PDT), chrischris201...@gmail.com wrote:
[snip]
>
> i try to follow some tutorial but i have that error :
>
> Traceback (most recent call last):
>   File "C:\Python27\test\test\earth.py", line 42, in 
> slope_array = np.ones_like(data_array) * nodataval
> TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
>
>
> first i define that lines of code :
>
> data_array = raster2array(filename)
> nodataval = getNoDataValue(filename)
>
> and the line with error :
>
> slope_array = np.ones_like(data_array) * nodataval
>
> how can i fix this error ?i change type field ?
>
> on the four prints:
>
> print(resolution)
> print(nodataval)
> print(type(data_array))
> print(data_array.shape)
>
> i take that exports :
>
> {'east-west': 0.0002778, 'north-south': 0.0002778}
> None
>
> (3601, 3601)

The TypeError error message is telling you that in the line

 slope_array = np.ones_like(data_array) * nodataval

you're attempting to multiply something of type "int" by something 
of type "NoneType".  And look, when you printed nodataval, you got "None".

So, the real question is why getNoDataValue is returning None.  To
answer that question, I would have to know something about the osgeo
package and your input file dem.tif, but unfortunately I don't.

-- 
To email me, substitute nowhere->runbox, invalid->com.
-- 
https://mail.python.org/mailman/listinfo/python-list


python (scipy) TypeError

2016-10-03 Thread chrischris201444
hello


i try to follow some tutorial but i have that error :

Traceback (most recent call last):
  File "C:\Python27\test\test\earth.py", line 42, in 
slope_array = np.ones_like(data_array) * nodataval
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'


first i define that lines of code :

data_array = raster2array(filename)
nodataval = getNoDataValue(filename)

and the line with error :

slope_array = np.ones_like(data_array) * nodataval

how can i fix this error ?i change type field ?

on the four prints:

print(resolution)
print(nodataval)
print(type(data_array))
print(data_array.shape)

i take that exports :

{'east-west': 0.0002778, 'north-south': 0.0002778}
None

(3601, 3601)

the full code :


from __future__ import division
from osgeo import gdal
from matplotlib.colors import ListedColormap
from matplotlib import colors
import sys
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import math

filename = 'dem.tif'

def getResolution(rasterfn):
raster = gdal.Open(rasterfn)
geotransform = raster.GetGeoTransform()
res = {"east-west": abs(geotransform[1]), 
   "north-south": abs(geotransform[5])}
return res

def raster2array(rasterfn):
raster = gdal.Open(rasterfn)
band = raster.GetRasterBand(1)
return band.ReadAsArray()

def getNoDataValue(rasterfn):
raster = gdal.Open(rasterfn)
band = raster.GetRasterBand(1)
return band.GetNoDataValue()

data_array = raster2array(filename)
nodataval = getNoDataValue(filename)
resolution = getResolution(filename)
print(resolution)
print(nodataval)

print(type(data_array))
print(data_array.shape)

num_rows = data_array.shape[0]
num_cols = data_array.shape[1]

slope_array = np.ones_like(data_array) * nodataval
aspect_array = np.ones_like(data_array) * nodataval

for i in range(1, num_rows - 1):
for j in range(1, num_cols - 1):
a = data_array[i - 1][j - 1]
b = data_array[i - 1][j]
c = data_array[i - 1][j + 1]
d = data_array[i][j - 1]
e = data_array[i][j]
f = data_array[i][j + 1]
g = data_array[i + 1][j - 1]
h = data_array[i + 1][j]
q = data_array[i + 1][j + 1]

vals = [a, b, c, d, e, f, g, h, q]

if nodataval in vals:
all_present = False
else:
all_present = True

if all_present == True:
dz_dx = (c + (2 * f) + q - a - (2 * d) - g) / (8 * 
resolution['east-west'])
dz_dy = (g + (2 * h) + q - a - (2 * b) - c) / (8 * 
resolution['north-south'])
dz_dx_sq = math.pow(dz_dx, 2)
dz_dy_sq = math.pow(dz_dy, 2)

rise_run = math.sqrt(dz_dx_sq + dz_dy_sq)
slope_array[i][j] = math.atan(rise_run) * 57.29578

aspect = math.atan2(dz_dy, (-1 * dz_dx)) * 57.29578
if aspect < 0:
aspect_array[i][j] = 90 - aspect
elif aspect > 90:
aspect_array[i][j] = 360 - aspect + 90
else:
aspect_array[i][j] = 90 - aspect

hist, bins = np.histogram(slope_array, bins=100, range=(0, 
np.amax(slope_array)))
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2
plt.bar(center, hist, align='center', width=width)
plt.xlabel('Slope (degrees)')
plt.ylabel('Frequency')
plt.show()

color_map = ListedColormap(['white', 'darkgreen', 'green', 'limegreen', 'lime', 
'greenyellow', 'yellow', 'gold', 
'orange', 'orangered', 'red'])

# range begins at negative value so that missing values are white
color_bounds = list(range(-3, math.ceil(np.amax(slope_array)), 1))
color_norm = colors.BoundaryNorm(color_bounds, color_map.N)

#Create the plot and colorbar
img = plt.imshow(slope_array, cmap = color_map, norm = color_norm)
cbar = plt.colorbar(img, cmap = color_map, norm = color_norm,
   boundaries = color_bounds, ticks = color_bounds)

#Show the visualization
plt.axis('off')
plt.title("Slope (degrees)")
plt.show()
plt.close()
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: working with ctypes and complex data structures

2016-10-03 Thread eryk sun
On Mon, Oct 3, 2016 at 2:35 PM, Michael Felt  wrote:
> On 02-Oct-16 23:44, eryk sun wrote:
>>   On Sun, Oct 2, 2016 at 5:50 PM, Michael Felt 
>> wrote:
>>
>>> b) what I am not understanding - as the basic documentation shows
>>> FOO.value as the way to set/get the value of a _field_
>>
>> You may be surprised when accessing simple-type fields such as c_int
>> and c_char_p. These simple types have getter and setter functions that
>> get called automatically whenever the type is used as a function
>> result, array index, or struct field. For example:
>
> OK - so lucky me - it "does not work" like earlier examples because I am
> referencing, generally, c_ulonglong - and these do not have a automatic
> getter/setter function? If not, how do I go about making one (preferably
> without needing to right a "method" for each and every _field_ in a class.

No, c_ulonglong is a simple (fundamental) type, which behaves just
like other simple types such as c_int or c_char_p.

On platform's with a 64-bit long, c_ulonglong is an alias for c_ulong
(i.e. type "L"). On the other hand, on 64-bit Windows, c_ulonglong is
an unsigned quad word (i.e. type "Q").

All simple types subclass ctypes._SimpleCData and define a `_type_`
code such as "c" for c_char. On 64-bit Linux the simple types are
defined as follows:

?: c_bool
c: c_char
z: c_char_p
u: c_wchar
Z: c_wchar_p
P: c_void_p

b: c_int8, c_byte
B: c_uint8, c_ubyte
h: c_int16, c_short
H: c_uint16, c_ushort
i: c_int32, c_int
I: c_uint32, c_uint
l: c_int64, c_long, c_longlong, c_ssize_t
L: c_uint64, c_ulong, c_ulonglong, c_size_t

f: c_float
d: c_double
g: c_longdouble

For convenience, simple types are automatically converted when
accessed as a function result, struct field, or array index. As I
mentioned previously, the only way around this behavior is to use a
subclass. A subclass doesn't get automatically converted because it
might define custom methods and attributes that need to be preserved.

>> I'd alias the type instead of defining a struct, e.g. `time_t =
>> c_long`. This preserves automatic conversion of the simple type.
>
> The reason for the not using alias is because a) I was trying to be more
> inline with the text of the include file. I will have to check the sizeof
> c_long (i.e., sizeof(long) in both 32 and 64-bit modes

I don't follow. Currently you wrap a c_int or c_long in a struct when
you could just use those types directly. You have to check the pointer
size, but then it's up to you what assumptions to make about the
target platform's integer sizes. Currently on a 64-bit system you're
assuming a Unix-style LP64 data model [1], in which a long is 64-bit.
That should be fine if you're writing Unix-specific code that doesn't
care about LLP64 Windows systems.

Wrapping the type in a struct provides more type safety, but if I
wanted that I'd create my own simple subclass. For example, assuming
time_t should be a signed integer that's the same size as a pointer:

class time_t(ctypes._SimpleCData):
if ctypes.sizeof(ctypes.c_void_p) == ctypes.sizeof(ctypes.c_longlong):
_type_ = ctypes.c_longlong._type_
elif ctypes.sizeof(ctypes.c_void_p) == ctypes.sizeof(ctypes.c_long):
_type_ = ctypes.c_long._type_
elif ctypes.sizeof(ctypes.c_void_p) == ctypes.sizeof(ctypes.c_int):
_type_ = ctypes.c_int._type_
# else raise AttributeError for missing _type_

[1]: https://en.wikipedia.org/wiki/64-bit_computing#64-bit_data_models
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is that forwards first or backwards first? (Re: unintuitive for-loop behavior)

2016-10-03 Thread breamoreboy
On Monday, October 3, 2016 at 12:53:55 PM UTC+1, Marko Rauhamaa wrote:
> Gregory Ewing:
> 
> > Turns out the only difference between first and reverse on that model
> > is whether you lift up a little ring on the shaft of the gear lever
> > prior to engagement.
> >
> > Who came up with *that* brilliant piece of user interface design I
> > don't know. It seems specifically designed to encourage velocity sign
> > errors when starting off...
> 
> Well, it could be worse. This layout is pretty traditional:
> 
> 1  3  5
> |  |  |
> +--+--+
> |  |  |
> 2  4  R
> 
> 
> Marko

There was the shift on the steering column on the 2CV, but then there's also 
this.


Traditional Italian military vehicle layout.

 1  3  5
 |  |  |
 +--+--+
 |  |  |
 2  4  F



Kindest regards.

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


Re: print to previous line in console

2016-10-03 Thread Skip Montanaro
> When we are printing to the console, is there a way to display to the 
> previous line in the console.

Check out the curses module:

https://docs.python.org/3.6/library/curses.html

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


print to previous line in console

2016-10-03 Thread udhay prakash pethakamsetty

Hi, 

\t is for tab(forward) space; and 
\r is for carriage return (back space)

When we are printing to the console, is there a way to display to the previous 
line in the console. 

We can achive that easily in file operations, But I want a solution in 
displaying on Console. 

regards

Udhay Prakash Pethakamsetty
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Copying a compiled Python from one system to another

2016-10-03 Thread Chris Angelico
On Tue, Oct 4, 2016 at 1:06 AM, Steve D'Aprano
 wrote:
> On Sun, 2 Oct 2016 04:45 pm, Paul Rubin wrote:
>
>> Steve D'Aprano  writes:
>>> Yes, this. You need gcc 4.8 or better to build CPython 3.6, and the most
>>> recent any of my systems support is 4.4.
>>
>> Building gcc takes a while but it's reasonably simple.  Just start it
>> going and read a book for a while.
>
> The dependencies needed to build 4.8 aren't available for my system. And
> there's no supported upgrade path.

At this point, I think you're at "try it and let us know". There's not
a lot more that can be predicted.

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


Re: Need help for the print() function with a better order

2016-10-03 Thread breamoreboy
On Sunday, October 2, 2016 at 2:12:39 AM UTC+1, 38016...@gmail.com wrote:
> I am trying to print a simple decision tree for my homework.
> The answer must keep in this format:
> 
> Top 7,4,0.95
> career gain = 100
>   1.Management 2, 3, 0.9709505944546686
>   2.Service 5, 1, 0.6500224216483541
> location gain = 100
>   1.Oregon 4, 1, 0.7219280948873623
>   2.California 3, 3, 1.0
> edu_level gain = 100
>   1.High School 5, 1, 0.6500224216483541
>   2.College 2, 3, 0.9709505944546686
> years_exp gain = 100
>   1.Less than 3 3, 1, 0.8112781244591328
>   2.3 to 10 2, 1, 0.9182958340544896
>   3.More than 10 2, 2, 1.0
> 
> Here is my code:
> features={'edu_level':['High School','College'],'career':
> ['Management','Service'],'years_exp':['Less than 3','3 to 10','More than 
> 10'],'location':['Oregon','California']}
> 
> print('Top 7,4,0.95')
> for key in features:
> print('{} gain = {}'.format(key,100))
> attributes_list=features[key]
> kargs={}
> for i in range(len(attributes_list)):
> kargs[key]=attributes_list[i]
> low=table.count('Low',**kargs)
> high=table.count('High',**kargs)
> print('\t{}.{} {}, {}, 
> {}'.format(i+1,attributes_list[i],low,high,entropy(low,high)))
> 
> I set all the gain as 100 now.But actually the gain must calculate with the 
> data below.
> For example, the career gain need the data of 'Management' and 'Service'.
> I don't know how to do.
> or Anyone can provide me a better logic?

This code cannot run as neither count nor entropy are defined.

You can loop around the features like this:-

for key, attributes_list in features.items():

'iteritems' as suggested by Peter Pearson is Python 2 only.

You can loop around your attributes with:-

for attribute in attributes_list:

If you need the index in the loop use the enumerate function 
https://docs.python.org/3/library/functions.html#enumerate

Kindest regards.

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


Re: working with ctypes and complex data structures

2016-10-03 Thread Michael Felt



On 02-Oct-16 23:44, eryk sun wrote:

  On Sun, Oct 2, 2016 at 5:50 PM, Michael Felt  wrote:

a) where is documentation on "CField"'s?

It's undocumented.

So I do not feel so bad about not finding anything :)

A CField is a data descriptor that accesses a
struct field with the given type, size, and offset. Like most
descriptors, it's meant to be accessed as an attribute of an instance,
not as an attribute of the type.

When accessed as an attribute of a struct type, the value returned is
the CField descriptor itself. One reason to reference the descriptor
is for its "offset" attribute, since there's no offsetof() in ctypes.
At least in this regard it should be documented.


b) what I am not understanding - as the basic documentation shows FOO.value
as the way to set/get the value of a _field_

You may be surprised when accessing simple-type fields such as c_int
and c_char_p. These simple types have getter and setter functions that
get called automatically whenever the type is used as a function
result, array index, or struct field. For example:
OK - so lucky me - it "does not work" like earlier examples because I am 
referencing, generally, c_ulonglong - and these do not have a automatic 
getter/setter function? If not, how do I go about making one (preferably 
without needing to right a "method" for each and every _field_ in a class.

 class Foo(ctypes.Structure):
 _fields_ = (('v', ctypes.c_int),)

 >>> foo = Foo()
 >>> foo.v = 5
 >>> foo.v
 5

You can use a subclass to avoid the getfunc's automatic conversion. For example;

 class my_int(ctypes.c_int):
 pass

 class Bar(ctypes.Structure):
 _fields_ = (('v', my_int),)

 >>> bar = Bar()
 >>> bar.v = 5
 >>> bar.v
 
 >>> bar.v.value
 5
I'll try it also with my c_int/c_uint fields - maybe these just work. If 
so, again - how do I get a c_ulonglong?



class time_t(Structure):
...
 if (maxsize > 2**32):
 _fields_ = [("v", c_long)]
 else:
 _fields_ = [("v", c_int)]

I'd alias the type instead of defining a struct, e.g. `time_t =
c_long`. This preserves automatic conversion of the simple type.
The reason for the not using alias is because a) I was trying to be more 
inline with the text of the include file.
I will have to check the sizeof c_long (i.e., sizeof(long) in both 32 
and 64-bit modes

Also, sys.maxsize is based on the platform's size_t type. That's
generally the same size as a pointer, but C doesn't require this.
Instead use sizeof(c_void_p), which will be 8 on a 64-bit platform and
4 on a 32-bit platform.

Thanks!


Also, while it's unrelated to your current problem, bear in mind that
int and long are both always 32-bit on Windows. c_int64 is a
cross-platform 64-bit integer.


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


Re: Copying a compiled Python from one system to another

2016-10-03 Thread Steve D'Aprano
On Sun, 2 Oct 2016 04:45 pm, Paul Rubin wrote:

> Steve D'Aprano  writes:
>> Yes, this. You need gcc 4.8 or better to build CPython 3.6, and the most
>> recent any of my systems support is 4.4.
> 
> Building gcc takes a while but it's reasonably simple.  Just start it
> going and read a book for a while.

The dependencies needed to build 4.8 aren't available for my system. And
there's no supported upgrade path.


-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: announcing fython

2016-10-03 Thread nicolasessisbreton
>Have you looked at f2py?
>There is also fortran magic for Jupyter notebooks
>f90wrap extends f2py to support modern Fortran

f2py and others are great to use static Fortran code, like LAPACK or BLAS.
By static, I mean that no change is necessary to the Fortran code.
Fython can do that too, and also addresses the use case of a dynamic Fortran 
code. I often go back and forth between the Python part and the Fython part of 
my code, tuning both as the project evolved.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python 3.5 amd64 and win32service

2016-10-03 Thread eryk sun
On Mon, Oct 3, 2016 at 1:26 PM, Nagy László Zsolt  wrote:
>
> Is it possible to write a win32 service with 64 bit python 3.5? The
> pywin32 package does exist on 3.5 64bit, but missing some modules:

Try pip installing the "pypiwin32" package.
-- 
https://mail.python.org/mailman/listinfo/python-list


Python 3.5 amd64 and win32service

2016-10-03 Thread Nagy László Zsolt

  Hello,

Is it possible to write a win32 service with 64 bit python 3.5? The
pywin32 package does exist on 3.5 64bit, but missing some modules:

>>> import win32service
Traceback (most recent call last):
  File "", line 1, in 
ImportError: DLL load failed:The specified module could not be found.

>>>

Missing modules: win32service win32event servicemanager

I have also tried the 32 bit version of Python. The 32 bit version does
have the missing modules, but the installer fails.  Even if I start it
as a system admin, I get this message:

LoadLibraryEx returned 1444544512, last error 0

The basic question: is it - at least in theory - possible to use 64 bit
python in a win32 service?

Thanks,

   Laszlo


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


ANN: parsita 1.0.0, a new parser combinator library

2016-10-03 Thread David Hagen
Parsita is a parser combinator library for Python. I wrote it because I 
missed the intuitive parser combinator library in Scala while trying to 
parse custom model file formats in Python. Parsita is focused on a clean 
grammar-like syntax, defining operators like `|` and `&` and functions like 
`opt` and `repsep`. It even allows for forward declarations of values 
through metaclass magic.

Available on PyPI: 
pip install parsita

Tutorial and examples on Github: 
https://github.com/drhagen/parsita

Obligatory JSON parser example:

```
from parsita import *

json_whitespace = r'[ \t\n\r]*'

class JsonStringParsers(TextParsers, whitespace=None):
quote = lit(r'\"') > (lambda _: '"')
reverse_solidus = lit(r'\\') > (lambda _: '\\')
solidus = lit(r'\/') > (lambda _: '/')
backspace = lit(r'\b') > (lambda _: '\b')
form_feed = lit(r'\f') > (lambda _: '\f')
line_feed = lit(r'\n') > (lambda _: '\n')
carriage_return = lit(r'\r') > (lambda _: '\r')
tab = lit(r'\t') > (lambda _: '\t')
uni = reg(r'\\u([0-9a-fA-F]{4})') > (lambda x: chr(int(x.group(1), 16)))

escaped = (quote | reverse_solidus | solidus | backspace | form_feed
   | line_feed | carriage_return | tab | uni)
unescaped = reg(r'[\u0020-\u0021\u0023-\u005B\u005D-\U0010]+')

string = '"' >> rep(escaped | unescaped) << '"' > ''.join


class JsonParsers(TextParsers, whitespace=json_whitespace):
number = reg(r'-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?') > float

false = lit('false') > (lambda _: False)
true = lit('true') > (lambda _: True)
null = lit('null') > (lambda _: None)

string = reg(json_whitespace) >> JsonStringParsers.string

array = '[' >> repsep(value, ',') << ']'

entry = string << ':' & value
obj = '{' >> repsep(entry, ',') << '}' > dict

value = number | false | true | null | string | array | obj
```
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is that forwards first or backwards first? (Re: unintuitive for-loop behavior)

2016-10-03 Thread BartC

On 03/10/2016 12:53, Marko Rauhamaa wrote:

Gregory Ewing :


Turns out the only difference between first and reverse on that model
is whether you lift up a little ring on the shaft of the gear lever
prior to engagement.

Who came up with *that* brilliant piece of user interface design I
don't know. It seems specifically designed to encourage velocity sign
errors when starting off...


Well, it could be worse. This layout is pretty traditional:

1  3  5
|  |  |
+--+--+
|  |  |
2  4  R


Yes, you get a funny grinding sound when attempting to change from 5th 
to '6th' at 70mph/110kph. Fortunately it doesn't actually go into reverse.


--
Bartc

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


Re: Is that forwards first or backwards first? (Re: unintuitive for-loop behavior)

2016-10-03 Thread alister
On Mon, 03 Oct 2016 22:10:52 +1300, Gregory Ewing wrote:

> Rustom Mody wrote:
>> My new car goes in reverse when I put it in first gear but only on
>> full-moon nights with the tank on reserve when the left light is
>> blinking
> 
> OT aside: When I went to take my current car (a manual) for a test
> drive, I had to stop and ask the dealer how to put it into reverse.
> 
> Turns out the only difference between first and reverse on that model is
> whether you lift up a little ring on the shaft of the gear lever prior
> to engagement.
> 
> Who came up with *that* brilliant piece of user interface design I don't
> know. It seems specifically designed to encourage velocity sign errors
> when starting off...

that sounds like typical Vauxhall & i never found it an issue when i had 
one

.
unlike my current car which supposedly requires extra force to move 
across the gate to reverse. I constantly find that it selects reverse 
without effort when not required, but goes into 1st when trying to select 
reverse. 

-- 
The Hollywood tradition I like best is called "sucking up to the stars."
-- Johnny Carson
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Is that forwards first or backwards first? (Re: unintuitive for-loop behavior)

2016-10-03 Thread Marko Rauhamaa
Gregory Ewing :

> Turns out the only difference between first and reverse on that model
> is whether you lift up a little ring on the shaft of the gear lever
> prior to engagement.
>
> Who came up with *that* brilliant piece of user interface design I
> don't know. It seems specifically designed to encourage velocity sign
> errors when starting off...

Well, it could be worse. This layout is pretty traditional:

1  3  5
|  |  |
+--+--+
|  |  |
2  4  R


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


Re: working with ctypes and complex data structures

2016-10-03 Thread Michael Felt



On 02-Oct-16 23:44, eryk sun wrote:

  On Sun, Oct 2, 2016 at 5:50 PM, Michael Felt  wrote:

>
>a) where is documentation on "CField"'s?

I will reply more later - just a quick thanks.

Not using maxsize will be good, also in a different patch - also 
specific to AIX.


This "thing" I am working is to:
a) document stuff (for a novice like myself)
b) have a better way to get system low-level statistics, comparable to 
Linux, where additions have been made to libc to get them.

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


Is that forwards first or backwards first? (Re: unintuitive for-loop behavior)

2016-10-03 Thread Gregory Ewing

Rustom Mody wrote:
My new car goes in reverse when I put it in first gear but only on full-moon 
nights with the tank on reserve when the left light is blinking


OT aside: When I went to take my current car (a manual)
for a test drive, I had to stop and ask the dealer how
to put it into reverse.

Turns out the only difference between first and reverse
on that model is whether you lift up a little ring on the
shaft of the gear lever prior to engagement.

Who came up with *that* brilliant piece of user interface
design I don't know. It seems specifically designed to
encourage velocity sign errors when starting off...

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


Re: unintuitive for-loop behavior

2016-10-03 Thread Gregory Ewing

Steve D'Aprano wrote:

x = str = 1
assert x == 1 and str == 1
del x, str
assert str  # succeeds
assert x  # NameError
x = str = 2  # create new bindings, or update existing ones?

Is it our conclusion that therefore Python creates a new binding for str
but not for x? Or that the evidence for x is "inconclusive"? Either answer
is illogical.


The assignment to 'str' must have created a new binding,
because the old one still exists, as evidenced by its
reappearance when we delete 'str'.

The situation as regards 'x' is inconclusive, but we can
find out by applying the closure test:

>>> x = 1
>>> f1 = lambda: x
>>> del x
>>> x = 2
>>> f2 = lambda: x
>>> print(f1(), f2())
(2, 2)

The second assignment to x must have updated the binding
established by the first one, because both closures see
the most recent value. (According to our definitions, this
is true *despite* the fact that we deleted x between times!)

However, things get a bit weird due to the dynamic nature
of the global and builtin namespaces:

>>> f1 = lambda: str
>>> str = 88
>>> f2 = lambda: str
>>> print(f1(), f2())
(88, 88)
>>> del str
>>> print(f1(), f2())
(, )

This is weird in a quantum-entanglement kind of way. It
appears as though the two closures have captured the
same binding, because at any given moment they both
see the same value. But *which* binding that is can
vary from one moment to the next!

I think the only way to make sense of this in terms of
the classical notions of bindings and lexical scoping
is to regard the global and builtin namespaces
together as a single lexical level, within which
dynamic lookup occurs.

By the way, Scheme implementations typically also treat
the global namespace in a more dynamic way than others.
However, in Scheme there is only a single global level,
so you don't get the same dynamic shadowing/unshadowing
behaviour.


Locals are certainly special. The language definition singles out binding[1]
to a variable inside a function as the trigger to treat it as a local,


As the above illustrates, there are also very real differences
between the way local and global bindings are captured
by closures. Whether those differences are considered
part of the language definition, I don't know. I suspect
Guido would regard them as artifacts of the implementation.

CPython seems to have punted on part of this by not allowing
you to delete a local name that's referenced by a nested
function, thus avoiding the issue of whether doing that should
be able to un-shadow a name further out.

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


Re: unintuitive for-loop behavior

2016-10-03 Thread Jussi Piitulainen
Antoon Pardon writes:

> Op 02-10-16 om 07:59 schreef Rustom Mody:
>>
>> You are explaining the mechanism behind the bug. Thanks. The bug
>> remains.  My new car goes in reverse when I put it in first gear but
>> only on full-moon nights with the tank on reserve when the left light
>> is blinking The engineer explains the interesting software bug in the
>> new PCB.  Interesting. But the bug remains
>>
>> Likewise here:
>>
>> [2 ** i for i in[1,2]] == [2**1, 2**2]
>>
>> yet this fails 
>>
>> [lambda x: x + i for i in [1,2]] == [lambda x:x+1, lambda x:x=2]
>>
>> is a bug for anyone including the OP of this thread

(That x=2 should be x+2.)

(And that == for functions needs to be understood mathematically. In
Python, even (lambda : 1) == (lambda : 1) may (must?) be False.)

> I once suggested that a list comprehension like [ for i in
> ] should be implemented as [(lambda i:)(i) for i in
> ].
>
> As far a I can see, it would behave as expected in all cases.

It's strictly circular as-is (the latter is an instance of the former),
and it needs spelled-out a bit in order to cover comprehensions of
multiple variables. I like it anyway.

On the other hand, fortunately, it's simple to *do* this in practice
when the need arises, without waiting for anyone to change the
language. (So is the default-parameter trick.)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyQt5, OpenGL, where to start, minimal example code?

2016-10-03 Thread Phil Thompson
On 3 Oct 2016, at 4:29 am, John Ladasky  wrote:
> 
> On Sunday, October 2, 2016 at 7:21:15 PM UTC-7, blue wrote:
>> You have here a PyQt5 Reference Guide 
>> http://pyqt.sourceforge.net/Docs/PyQt5/index.html
>> Some example can be found here 4 and 5 
>> http://codeprogress.com/python/libraries/pyqt/
> 
> That's a nice page of examples, but there are no OpenGL examples.
> 
>> Support for OpenGL http://pyqt.sourceforge.net/Docs/PyQt5/opengl.html told 
>> us:
>> 
>> When compiled against Qt v5.1 or later, PyQt5 implements a set of either 
>> desktop QOpenGL bindings or OpenGL ES v2 bindings depending on how Qt was 
>> configured. This removes the dependency on any third-party OpenGL bindings 
>> such as PyOpenGL.
>> 
>> At the moment the desktop bindings are for OpenGL v2.0 and are mostly 
>> complete. Other versions will be added in later releases. If there are calls 
>> which you need, but are currently unsupported, then please ask for the 
>> support to be added.
> 
> I found that page many days ago.  I am not sure whether OpenGL 4.5, which is 
> what Ubuntu installed for me, is an extension of OpenGL ES v2, or something 
> completely different.
> 
> PyQt5 seems to be at least nominally aware of recent versions of OpenGL, and 
> it knows that I have version 4.5 -- since my program went looking for a 
> module called "QOpenGLFunctions_4_5_Compatibility".  On this page...
> 
> http://doc.qt.io/qt-5/qtgui-module.html
> 
> ...the Qt5 QTGui documentation lists a plethora of functions to retrieve 
> OpenGL "specifications" and "compatibility profiles", ranging from OpenGL 1.0 
> through 4.5.
> 
> Note, these are not PyQt docs, they are for Qt.  I have been sometimes 
> frustrated by the fact that the PyQt modules do not appear to have a 
> one-to-one mapping with the hierarchy of Qt itself.
> 
>> Obtaining an object that implements the bindings for a particular OpenGL 
>> version and profile is done in the same way as it is done from C++, i.e. by 
>> calling versionFunctions(). In addition, the bindings object also contains 
>> attributes corresponding to all of the OpenGL constants.
> 
> And as you can see: trying to call versionFunctions() is exactly where my 
> program failed.

Try passing a QOpenGLVersionProfile object to versionFunctions() that has a 
version set to one supported by PyQt.

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


Re: unintuitive for-loop behavior

2016-10-03 Thread Antoon Pardon
Op 02-10-16 om 07:59 schreef Rustom Mody:
>
> You are explaining the mechanism behind the bug. Thanks. The bug remains.
> My new car goes in reverse when I put it in first gear but only on full-moon 
> nights with the tank on reserve when the left light is blinking
> The engineer explains the interesting software bug in the new PCB.
> Interesting. But the bug remains
>
> Likewise here:
>
> [2 ** i for i in[1,2]] == [2**1, 2**2]
>
> yet this fails 
>
> [lambda x: x + i for i in [1,2]] == [lambda x:x+1, lambda x:x=2]
>
> is a bug for anyone including the OP of this thread
>
I once suggested that a list comprehension like [ for i in ] 
should
be implemented as [(lambda i:)(i) for i in ].

As far a I can see, it would behave as expected in all cases.

-- 
Antoon


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


Re: unintuitive for-loop behavior

2016-10-03 Thread Gregory Ewing

Chris Angelico wrote:

The only way to prove that something is a new binding is to
demonstrate that, when this binding is removed, a previous one becomes
visible.


Or capture them both with closures and show that each
closure sees a different version of the binding.

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


Re: unintuitive for-loop behavior

2016-10-03 Thread Gregory Ewing

Steve D'Aprano wrote:

No it doesn't mean that at all. The result you see is compatible with *both*
the "update existing slot" behaviour and "create a new slot" behavior.


We're getting sidetracked talking about slots here.
It's not really relevant. The point is that there is
only *one* binding for x here, and the second
assignment is updating that binding, not creating a
new binding. If it were otherwise, something different
would have been printed.

This is a high-level concept that has nothing to do
with implementation details. It's the *definition*
of what's meant by the terms "new binding" and
"existing binding".


Objection: I predict that you're going to object that despite the `del x`
and the assertion, *if* this code is run inside a function, the "x slot"
actually does still exist. It's not "really" deleted, the interpreter just
makes sure that the high-level behaviour is the same as if it actually were
deleted.


Actually, it's the same as if it were *not* deleted.

Interestingly, if you run it inside a function, something different
again happens:

>>> def f():
...  x = 0
...  f1 = lambda: x
...  del x
...  assert 'x' not in locals()
...  x = 1
...  f2 = lambda: x
...  print(f1(), f2())
...
SyntaxError: can not delete variable 'x' referenced in nested scope

So no, I'm not going to raise that objection. :-)


In IronPython, you could have the following occur in a function locals, just
as it could happen CPython for globals:

- delete the name binding "x"
- which triggers a dictionary resize
- bind a value to x again
- because the dictionary is resized, the new "slot" for x is in a 
  completely different position of the dictionary to the old one


Which is all completely irrelevant. The important thing is
what's seen by closures created at different times within
that function.

I don't have an IronPython handy to try it, but if you do,
I'd be interested to know the result. (I'm fairly sure it
would still show same-binding behaviour, but you never
know.)


Your code
works the same way whether it is executed inside a function or at the
global top level,


I've never claimed otherwise.


It's not currently possible to observe the other behaviour in
Python, because the only way to create new bindings for local
names is to enter a function.


Not at all. Delete a name, and the binding for that name is gone. Now assign
to that name again, and a new binding must be created,


No, you still don't understand what "new binding" means. If it
truly were creating a new binding, the observable behaviour
would be different, *by definition*.


I'm especially confused because you seem to be arguing that by using an
implementation which CPython already uses, for-loops would behave
differently.


No, the implementation I'm talking about is definitely *not*
being used already.


A thunk is not really well-defined in Python, because it doesn't exist, and
therefore we don't know what properties it will have.


Just call it a function, then. Here's an example of the
transformation I'm talking about.

Before:

def f():
  funcs = []
  for x in range(3):
funcs.append(lambda: x)
  for g in funcs:
print g()

After:

def f():
  funcs = []
  def _body(x):
funcs.append(lambda: x)
  for _x in range(3):
_body(_x)
  for g in funcs:
print g()


In Python, the most obvious gotcha would be that if for-loops introduced
their own scope, you would have to declare any other variables in the outer
scope nonlocal.


I'm not suggesting they should. If the above transformation
were used as an actual implementation, the compiler would
have to introduce implicit 'nonlocal' declarations as needed
to keep the semantics of assignments within the loop body
the same.


(Incidentally, this is why some people describe Python's
behaviour here as "broken". They ask -- it works perfectly
well in these other languages, why is Python different?)


Define "it". Python works perfectly well too.


So you think that useless behaviour is just as good as
useful behaviour?


It just works differently from
what some people expect, especially if they don't think about the meaning
of what they're doing and want the interpreter to DWIM.


The point is that if they write the analogous thing in
any of those other languages, it *does* DWTM. So I don't
blame anyone for thinking that Python has some explaining
to do.


"The trick with cells" -- what trick do you mean?


Each time around the loop, if the loop variable is in a
cell, instead of updating the contents of that cell (as
a normal assigment would do), create a new cell.

I don't know how to explain it any more clearly than
that. I can't write it in Python, because Python doesnt
currently have any way to express that operation. I
can't even do it with bytecode, because the bytecodes
that would be needed don't exist.

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