Re: macOS specific - reading calendar information

2018-03-15 Thread Jan Erik Moström

On 14 Mar 2018, at 21:40, Larry Martell wrote:

I've been trying to find some example of how to read calendar info on 
macOS
but I haven't found anything ... I'm probably just bad at searching 
!!


What I want to do is to read calendar info for a date range. Does 
anyone

know of an example of how to do this?



What does 'read calendar info' mean? What exactly are you trying to 
read from?


I would like to read what calendar events I have on a range of days. I 
would like to get the data from whatever storage Calendar use, in my 
personal case I sync to iCloud.


An example would be something along these lines

x = getcalendarevents('2018-03-15', '2018-03-25')

or even better

x = getcalendarevents('2018-03-15', '2018-03-25',[calendar1, calendar2, 
...])



and x would contain some data structure that gives me the events that 
occurs from 2018-03-15 up to and including 2018-03-25, each event 
containing at least start/end time, title, place, calendar to which the 
event belong.


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


Re: macOS specific - reading calendar information

2018-03-15 Thread Christian Gollwitzer

Am 15.03.18 um 08:32 schrieb Jan Erik Moström:
I would like to read what calendar events I have on a range of days. I 
would like to get the data from whatever storage Calendar use, in my 
personal case I sync to iCloud.


An example would be something along these lines

x = getcalendarevents('2018-03-15', '2018-03-25')

or even better

x = getcalendarevents('2018-03-15', '2018-03-25',[calendar1, calendar2, 
...])



and x would contain some data structure that gives me the events that 
occurs from 2018-03-15 up to and including 2018-03-25, each event 
containing at least start/end time, title, place, calendar to which the 
event belong.


I assume you mean the calendar app included within OSX. It can be 
scripted, start from here: 
https://developer.apple.com/library/content/documentation/AppleApplications/Conceptual/CalendarScriptingGuide/index.html



The native script language is Apple Script or JavaScript. If you want to 
control it from Python, you need a bridge. I have no experience with it, 
but a quick Google search reveals 
https://pypi.python.org/pypi/py-applescript and 
https://docs.python.org/2/library/macosa.html


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


Re: Python gotcha of the day

2018-03-15 Thread Thomas Jollans
On 2018-03-15 07:11, Ben Finney wrote:
> Steven D'Aprano  writes:
> 
>> py> """\""
>> '"'
> 
> That's an empty string delimited by ‘"’; followed by a double-quote
> character, escaped, delimited by ‘"’; followed by two more empty
> strings. They concatenate to a single one-character string.
> 
> Equivalent to
> 
> "" + "\"" + "" + ""
> 
> without the ‘+’ operations.
> 
>> If nobody gets the answer, I shall reveal all later.
> 
> My interpretation may not be how the language defines it; but it does
> match the result!
> 

Then riddle me this:

if """\"" is equivalent to "" + "\"" + "" + "", then why isn't
""" \""" """ equivalent to "" + " \"" + " " + ""?

As I said earlier: I initially thought the way you're thinking, but got
stuck at that question and had to back-track my reasoning :-)

T

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


Re: Homebrew changed default Python to python 3!

2018-03-15 Thread INADA Naoki
FYI, they reverted python->python3 symlink. python command is now
Python 2 again.
https://discourse.brew.sh/t/python-and-pep-394/1813

Even though this revert, it is significant step:

* many formulas dropped `depends_on "python"`.  Python 2 was installed
often by dependency before
  but it's rare for now.

* Some formulas (including vim) keep `depends_on "python".
  It means they are depending on Python 3 instead of 2.
  It makes vim plugin authors can consider about dropping Python 2 support.
   (vim is linked with Python 3 on recent Ubuntu already)

I hope Apple will provide "/usr/bin/python2" at least in next macOS,
to allow people using "python2" shebang
for scripts support only Python 2.
(And I hope Python 3.6 (or 3.7) is pre-installed in next macOS)...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Enumerating all 3-tuples (Posting On Python-List Prohibited)

2018-03-15 Thread Ben Bacarisse
Lawrence D’Oliveiro  writes:

> On Thursday, March 15, 2018 at 2:56:24 PM UTC+13, Ben Bacarisse wrote:
>>
>> Lawrence D’Oliveiro writes:
>> 
>>> On Wednesday, March 14, 2018 at 2:18:24 PM UTC+13, Ben Bacarisse wrote:
>>>
 Lawrence D’Oliveiro writes:
 
 The original problem -- triples of natural numbers -- is
 not particularly hard, but the general problem -- enumerating n-tuples
 of some sequence -- is more interesting because it is a bit harder.
>>>
>>> It’s not harder--it’s exactly the same difficulty. You iterate the
>>> naturals, then interpose a function mapping them onto the set that you
>>> really want to use.
>> 
>> Yes, I said exactly that a couple of messages ago.
>
> I see. So you said it is a bit harder, and you also said it’s not
> harder at all. Got it.

Yes, I was not clear.  It was the point about mapping from a solution
that uses the natural numbers that's I mentioned before.  The "bit
harder" comes from generalising to n-tuples.

(I get the feeling I should apologise for something because I think I
have annoyed or irritated you.  I'm sure I don't always get the right
tone but I really hope I've not been rude.  I'm sorry if I have been.)

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


List slicing on Python 2.7

2018-03-15 Thread Arkadiusz Bulski
I have a custom class (a lazy list-like container) that needs to support
slicing. The __getitem__ checks if index is of slice type, and does a list
comprehension over individual integer indexes. The code works fine on
Python 3 but fails on 2.7, both CPython and PyPy. The print inside
__getitem__ doesnt even get executed when its a slice. Does 2.7 have
different object model, where slices are handled by a different method than
__getitem__?

The implementation and error log
https://github.com/construct/construct/blob/8839aac2b68c9e8240e9d9c041a196b0a7aa7d9b/construct/core.py#L4785-L4796
https://github.com/construct/construct/blob/8839aac2b68c9e8240e9d9c041a196b0a7aa7d9b/tests/test_core.py#L1148
https://travis-ci.org/construct/construct/jobs/353782126#L887

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


Re: Enumerating all 3-tuples

2018-03-15 Thread Denis Kasak

On 2018-03-13 23:56, Denis Kasak wrote:

On 2018-03-10 02:13, Steven D'Aprano wrote:


But I've stared at this for an hour and I can't see how to extend the
result to three coordinates. I can lay out a grid in the order I want:

1,1,1   1,1,2   1,1,3   1,1,4   ...
2,1,1   2,1,2   2,1,3   2,1,4   ...
1,2,1   1,2,2   1,2,3   1,2,4   ...
3,1,1   3,1,2   3,1,3   3,1,4   ...
2,2,1   2,2,2   2,2,3   2,2,4   ...
...

and applying Cantor's diagonal order will give me what I want, but 
damned

if I can see how to do it in code.



[snip]


The triples can be viewed as a pair of a pair and a natural number:

(1,1),1 (1,1),2 (1,1),3 ...
(2,1),1 (2,1),2 (2,1),3 ...
(1,2),1 (1,2),2 (1,2),3 ...
   .   .   .
   .   .   .
   .   .   .

[snip]

def c3(i):
"""
Inverse of the Cantor pairing function generalization to 
triples,

mapping N → N×N×N.
"""
n, m = c(i)
return c(n) + (m,)


In fact, extending this idea further, we can view the grid as a 
Cartesian product of two sets: the natural numbers and an arbitrary 
enumerable set. In your intended grid layout, the natural numbers were 
put (in their usual ordering) on the horizontal axis and the 2-tuples 
given by the pairing function on the vertical axis.


However, diagonalizing this grid allows us to enumerate the Cartesian 
product itself, which means we can repeat the process by using this 
enumeration as the new vertical axis. Therefore, this process 
generalizes naturally to an arbitrary number of dimensions:


def cr(i, d=2):
"""
Inverse of the Cantor pairing function generalization to 
d-tuples,

mapping N → N^d.
"""
if d == 1:
return i
elif d == 2:
return c(i)
else:
n, m = c(i)
return cr(n, d-1) + (m,)


>>> def first_ten(d):
...return [cr(i, d) for i in range(1, 11)]

>>> for d in range(2, 5):
... pprint(first_ten(d))
[(1, 1), (2, 1), (1, 2), (3, 1), (2, 2), (1, 3), (4, 1), (3, 2), (2, 
3), (1, 4)]

[(1, 1, 1),
(2, 1, 1),
(1, 1, 2),
(1, 2, 1),
(2, 1, 2),
(1, 1, 3),
(3, 1, 1),
(1, 2, 2),
(2, 1, 3),
(1, 1, 4)]
[(1, 1, 1, 1),
(2, 1, 1, 1),
(1, 1, 1, 2),
(1, 1, 2, 1),
(2, 1, 1, 2),
(1, 1, 1, 3),
(1, 2, 1, 1),
(1, 1, 2, 2),
(2, 1, 1, 3),
(1, 1, 1, 4)]


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


number of loops

2018-03-15 Thread michealmancini
I would like to have this offer 6 guesses, but instead it gives one guess and 
prints the if statement/output 6 timesany ideas where I went wrong?

import random

number_of_guesses = 0

print ('Hello! what is your name?')
my_name=input()
print (my_name + "  " + 'sounds like the name of my next opponent')
print ('Shall we play?')

yes_or_no = input()

if yes_or_no == 'yes':
print ('ok! guess my number')
else:
print ('log off and go home')

my_number=random.randint(1,100)

your_guess=input()
your_guess=int(your_guess)

for number in range(6):
if your_guess > my_number:
print ('nope, too high')
if your_guess < my_number:
print ('nope, too low')
if your_guess == my_number:
break

if your_guess == my_number:
number_of_guesses=str(number_of_guesses)
print ('good job, you guessed correctly')
else:
print('nope, you lose')

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


Re: List slicing on Python 2.7

2018-03-15 Thread Vlastimil Brom
2018-03-15 12:54 GMT+01:00 Arkadiusz Bulski :
> I have a custom class (a lazy list-like container) that needs to support
> slicing. The __getitem__ checks if index is of slice type, and does a list
> comprehension over individual integer indexes. The code works fine on
> Python 3 but fails on 2.7, both CPython and PyPy. The print inside
> __getitem__ doesnt even get executed when its a slice. Does 2.7 have
> different object model, where slices are handled by a different method than
> __getitem__?
>
> The implementation and error log
> https://github.com/construct/construct/blob/8839aac2b68c9e8240e9d9c041a196b0a7aa7d9b/construct/core.py#L4785-L4796
> https://github.com/construct/construct/blob/8839aac2b68c9e8240e9d9c041a196b0a7aa7d9b/tests/test_core.py#L1148
> https://travis-ci.org/construct/construct/jobs/353782126#L887
>
> --
> ~ Arkadiusz Bulski
> --
> https://mail.python.org/mailman/listinfo/python-list

Hi,
it looks like, the older method __getslice__ is still used in python 2.7
cf.:
https://docs.python.org/2/reference/datamodel.html#object.__getslice__

You might need to implement this method in your class as well for
compatibility with python 2.

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


Re: List slicing on Python 2.7

2018-03-15 Thread Ned Batchelder

On 3/15/18 9:57 AM, Vlastimil Brom wrote:

2018-03-15 12:54 GMT+01:00 Arkadiusz Bulski :

I have a custom class (a lazy list-like container) that needs to support
slicing. The __getitem__ checks if index is of slice type, and does a list
comprehension over individual integer indexes. The code works fine on
Python 3 but fails on 2.7, both CPython and PyPy. The print inside
__getitem__ doesnt even get executed when its a slice. Does 2.7 have
different object model, where slices are handled by a different method than
__getitem__?

The implementation and error log
https://github.com/construct/construct/blob/8839aac2b68c9e8240e9d9c041a196b0a7aa7d9b/construct/core.py#L4785-L4796
https://github.com/construct/construct/blob/8839aac2b68c9e8240e9d9c041a196b0a7aa7d9b/tests/test_core.py#L1148
https://travis-ci.org/construct/construct/jobs/353782126#L887

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

Hi,
it looks like, the older method __getslice__ is still used in python 2.7
cf.:
https://docs.python.org/2/reference/datamodel.html#object.__getslice__

You might need to implement this method in your class as well for
compatibility with python 2.




Python 2 will use __getitem__ for slices:

    $ python2.7
    Python 2.7.10 (default, May 30 2015, 12:06:13)
    [GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> class Sliceable(object):
    ... def __getitem__(self, thing):
    ... print type(thing)
    ... print thing
    ...
    >>> Sliceable()[1:5]
    
    slice(1, 5, None)
    >>> Sliceable()[:]
    
    slice(None, None, None)
    >>>

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


Re: number of loops

2018-03-15 Thread Bob Gailer
On Mar 15, 2018 9:30 AM,  wrote:
>
> I would like to have this offer 6 guesses, but instead it gives one guess
and prints the if statement/output 6 timesany ideas where I went wrong?

I suggest you conduct a walk-through. That means pointing using a pencil or
a mouse pointer at each statement and noticing what it does. pay attention
to what happens when the loop repeats.

This will do more for you than if I just tell you the answer.
>
> import random
>
> number_of_guesses = 0
>
> print ('Hello! what is your name?')
> my_name=input()
> print (my_name + "  " + 'sounds like the name of my next opponent')
> print ('Shall we play?')
>
> yes_or_no = input()
>
> if yes_or_no == 'yes':
> print ('ok! guess my number')
> else:
> print ('log off and go home')
>
> my_number=random.randint(1,100)
>
> your_guess=input()
> your_guess=int(your_guess)
>
> for number in range(6):
> if your_guess > my_number:
> print ('nope, too high')
> if your_guess < my_number:
> print ('nope, too low')
> if your_guess == my_number:
> break
>
> if your_guess == my_number:
> number_of_guesses=str(number_of_guesses)
> print ('good job, you guessed correctly')
> else:
> print('nope, you lose')
>
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: urllib.request.urlopen fails with https

2018-03-15 Thread Irv Kalb
On Mar 14, 2018, at 9:54 PM, Gregory Ewing  wrote:
> 
> Chris Angelico wrote:
>> That means going back to the original problem: "how do we get a usable
>> stock price API?".
> 
> Does it have to be stock prices in particular?
> Or just some simple piece of data that demonstrates
> the principles of fetching a url and parsing the
> result?
> 
> -- 
> Greg
> -- 

I am the OP.  No, it does not have to be stock prices.  I used stock prices 
because it made for a very clear example in my curriculum.  In my class, I demo 
how we can write a small Python program to "pretend to be a browser" and get a 
full page of html, then I talk about how you can use an API with a small Python 
program to get just the data you really want.  I found a Yahoo API that did 
exactly what I wanted, and that has worked for years - but now Yahoo has 
cancelled that service.  I thought it would be simple to find another simple 
API to get a stock price but I haven't found one.  All the ones that do work 
seem to require https, which doesn't work easily with url lib.request.urlopen.

I do use other API's like openweathermap.org to get weather data and 
api.fixer.io  to get currency exchange rates.   I get the 
data back and work through parsing the results.

I am still very interested in getting a stock quote example but If you have 
other examples that have a URL that is http based, I am interested. 

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


Re: List slicing on Python 2.7

2018-03-15 Thread Arkadiusz Bulski
Found the answer on stack overflow. Some types on some runtimes (builtins
and on Python 2) use another method __getslice__ instead of __getitem__.
https://docs.python.org/2/reference/datamodel.html#object.__getslice__


czw., 15 mar 2018 o 12:54 użytkownik Arkadiusz Bulski 
napisał:

> I have a custom class (a lazy list-like container) that needs to support
> slicing. The __getitem__ checks if index is of slice type, and does a list
> comprehension over individual integer indexes. The code works fine on
> Python 3 but fails on 2.7, both CPython and PyPy. The print inside
> __getitem__ doesnt even get executed when its a slice. Does 2.7 have
> different object model, where slices are handled by a different method than
> __getitem__?
>
> The implementation and error log
>
> https://github.com/construct/construct/blob/8839aac2b68c9e8240e9d9c041a196b0a7aa7d9b/construct/core.py#L4785-L4796
>
> https://github.com/construct/construct/blob/8839aac2b68c9e8240e9d9c041a196b0a7aa7d9b/tests/test_core.py#L1148
> https://travis-ci.org/construct/construct/jobs/353782126#L887
>
> --
> ~ Arkadiusz Bulski
>
-- 
~ Arkadiusz Bulski
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: List slicing on Python 2.7

2018-03-15 Thread Peter Otten
Ned Batchelder wrote:

> On 3/15/18 9:57 AM, Vlastimil Brom wrote:
>> 2018-03-15 12:54 GMT+01:00 Arkadiusz Bulski :
>>> I have a custom class (a lazy list-like container) that needs to support
>>> slicing. The __getitem__ checks if index is of slice type, and does a
>>> list comprehension over individual integer indexes. The code works fine
>>> on Python 3 but fails on 2.7, both CPython and PyPy. The print inside
>>> __getitem__ doesnt even get executed when its a slice. Does 2.7 have
>>> different object model, where slices are handled by a different method
>>> than __getitem__?
>>>
>>> The implementation and error log
>>> 
https://github.com/construct/construct/blob/8839aac2b68c9e8240e9d9c041a196b0a7aa7d9b/construct/core.py#L4785-L4796
>>> 
https://github.com/construct/construct/blob/8839aac2b68c9e8240e9d9c041a196b0a7aa7d9b/tests/test_core.py#L1148
>>> https://travis-ci.org/construct/construct/jobs/353782126#L887
>>>
>>> --
>>> ~ Arkadiusz Bulski
>>> --
>>> https://mail.python.org/mailman/listinfo/python-list
>> Hi,
>> it looks like, the older method __getslice__ is still used in python 2.7
>> cf.:
>> https://docs.python.org/2/reference/datamodel.html#object.__getslice__
>>
>> You might need to implement this method in your class as well for
>> compatibility with python 2.
>>
>>
> 
> Python 2 will use __getitem__ for slices:
> 
>  $ python2.7
>  Python 2.7.10 (default, May 30 2015, 12:06:13)
>  [GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
>  Type "help", "copyright", "credits" or "license" for more information.
>  >>> class Sliceable(object):
>  ... def __getitem__(self, thing):
>  ... print type(thing)
>  ... print thing
>  ...
>  >>> Sliceable()[1:5]
>  
>  slice(1, 5, None)
>  >>> Sliceable()[:]
>  
>  slice(None, None, None)
>  >>>

__getslice__() takes precedence, and the OP subclasses list:

$ python
Python 2.7.6 (default, Nov 23 2017, 15:49:48) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class A(list):
... def __getitem__(self, index): return index
... 
>>> a = A()
>>> a[:]
[]
>>> a[::]
slice(None, None, None)
>>> A.__getslice__ = lambda self, *args: args
>>> a[:]
(0, 9223372036854775807)


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


Context manager on method call from class

2018-03-15 Thread Joseph L. Casale
I have a class which implements a context manager, its __init__
has a signature and the __enter__ returns an instance of the
class.

Along with several methods which implement functionality on
the instance, I have one method which itself must open a context
manager against a call on an instance attribute. This context manager
does not return an instance of itself, it merely opens a context.

I am not thrilled about is the implementation I have used and I
am wondering if there is a better way. It's been a long time since
I have worked in Python and I am probably overlooking something
obvious. Syntactically I achieve what I want in use, but it looks awkward
in its implementation. How can I clean up the first class and decorator
to implement the functionality on a method in the Foo class?

class MethodContextManager:
def __init__(self, obj, key, value):
self.obj = obj
self.key = key
self.value = value

def __enter__(self):
self.obj.some_method(key, value)

def __exit__(self, exc_type, exc_val, exc_tb):
self.obj.another_method()


def method_context_manager(func):
def wrapper(self, key, value):
return MethodContextManager(self.instance, key, value)
return wrapper


class Foo:
def __init__(self, bar):
self.bar = bar
self.instance = None

def __enter__(self):
self.instance = SomeFunc(this.bar)

return self

def __exit__(self, exc_type, exc_val, exc_tb):
# Cleanup...

@method_context_manager
def baz(self, key, value):
pass


with Foo(bar) as foo:
foo.other_call()
with foo.baz(42, "a"):
foo.other_call()
with foo.baz(420, None):
foo.other_call()
foo.other_call()
foo.other_call()
foo.other_call()
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Context manager on method call from class

2018-03-15 Thread Rob Gaddi

On 03/15/2018 11:17 AM, Joseph L. Casale wrote:

I have a class which implements a context manager, its __init__
has a signature and the __enter__ returns an instance of the
class.

Along with several methods which implement functionality on
the instance, I have one method which itself must open a context
manager against a call on an instance attribute. This context manager
does not return an instance of itself, it merely opens a context.

I am not thrilled about is the implementation I have used and I
am wondering if there is a better way. It's been a long time since
I have worked in Python and I am probably overlooking something
obvious. Syntactically I achieve what I want in use, but it looks awkward
in its implementation. How can I clean up the first class and decorator
to implement the functionality on a method in the Foo class?


> [snip]

from contextlib import contextmanager.

Then you just use the @contextmanager decorator on a function, have it 
set up, yield the context you want, and clean up after.


--
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Python gotcha of the day

2018-03-15 Thread Ben Finney
Thomas Jollans  writes:

> Then riddle me this:
>
> if """\"" is equivalent to "" + "\"" + "" + "", then why isn't
> """ \""" """ equivalent to "" + " \"" + " " + ""?

Who can say? I was only asked for an explanation, not a consistent one
:-)

Perhaps it's a micro-optimisation, to create more empty strings that can
be discarded quickly. Perhaps not.

> As I said earlier: I initially thought the way you're thinking, but got
> stuck at that question and had to back-track my reasoning :-)

I was not hindered by the burden to make my explanation work for
everything, just for the one example presented. This allowed me to
quickly get back to feeding my goldfish.

-- 
 \   “What do religious fundamentalists and big media corporations |
  `\   have in common? They believe that they own culture, they are so |
_o__) self-righteous about it …” —Nina Paley, 2011 |
Ben Finney

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


Re: Context manager on method call from class

2018-03-15 Thread Joseph L. Casale
From: Python-list  on 
behalf of Rob Gaddi 
Sent: Thursday, March 15, 2018 12:47 PM
To: [email protected]
Subject: Re: Context manager on method call from class
    
> from contextlib import contextmanager.
> 
> Then you just use the @contextmanager decorator on a function, have it 
> set up, yield the context you want, and clean up after.

Nice, all of what I wrote replaced with three lines:)

Thank you,
jlc
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: List slicing on Python 2.7

2018-03-15 Thread Ned Batchelder

On 3/15/18 12:35 PM, Peter Otten wrote:

Ned Batchelder wrote:


On 3/15/18 9:57 AM, Vlastimil Brom wrote:

2018-03-15 12:54 GMT+01:00 Arkadiusz Bulski :

I have a custom class (a lazy list-like container) that needs to support
slicing. The __getitem__ checks if index is of slice type, and does a
list comprehension over individual integer indexes. The code works fine
on Python 3 but fails on 2.7, both CPython and PyPy. The print inside
__getitem__ doesnt even get executed when its a slice. Does 2.7 have
different object model, where slices are handled by a different method
than __getitem__?

The implementation and error log


https://github.com/construct/construct/blob/8839aac2b68c9e8240e9d9c041a196b0a7aa7d9b/construct/core.py#L4785-L4796
https://github.com/construct/construct/blob/8839aac2b68c9e8240e9d9c041a196b0a7aa7d9b/tests/test_core.py#L1148

https://travis-ci.org/construct/construct/jobs/353782126#L887

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

Hi,
it looks like, the older method __getslice__ is still used in python 2.7
cf.:
https://docs.python.org/2/reference/datamodel.html#object.__getslice__

You might need to implement this method in your class as well for
compatibility with python 2.



Python 2 will use __getitem__ for slices:

  $ python2.7
  Python 2.7.10 (default, May 30 2015, 12:06:13)
  [GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
  Type "help", "copyright", "credits" or "license" for more information.
  >>> class Sliceable(object):
  ... def __getitem__(self, thing):
  ... print type(thing)
  ... print thing
  ...
  >>> Sliceable()[1:5]
  
  slice(1, 5, None)
  >>> Sliceable()[:]
  
  slice(None, None, None)
  >>>

__getslice__() takes precedence, and the OP subclasses list:

$ python
Python 2.7.6 (default, Nov 23 2017, 15:49:48)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.

class A(list):

... def __getitem__(self, index): return index
...

a = A()
a[:]

[]

a[::]

slice(None, None, None)

A.__getslice__ = lambda self, *args: args
a[:]

(0, 9223372036854775807)




Another good reason not to subclass list.

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


Re: Python installer hangs in Windows 7

2018-03-15 Thread simon . wonng
On Monday, December 4, 2017 at 12:44:48 PM UTC-8, [email protected] wrote:
> Same with me, except that I tried to install Python 3.6.3. Unchecking 
> "Install launcher for all users" helped, however.

This worked for me, thanks!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: number of loops

2018-03-15 Thread Dan Stromberg
On Thu, Mar 15, 2018 at 8:25 AM, Bob Gailer  wrote:
> On Mar 15, 2018 9:30 AM,  wrote:
>>
>> I would like to have this offer 6 guesses, but instead it gives one guess
> and prints the if statement/output 6 timesany ideas where I went wrong?
>
> I suggest you conduct a walk-through. That means pointing using a pencil or
> a mouse pointer at each statement and noticing what it does. pay attention
> to what happens when the loop repeats.

I'm guessing a GUI or curses debugger would help quite a bit.   EG's:
winpdb, pudb.  winpdb is cross-platform, despite the name.  pudb might
not work on Microsoft Windows, though perhaps it would in Cygwin.

These, and many other debuggers allow you to single step through your
code and see what the execution order is, one statement at a time.
It's a pretty valuable learning experience early on, IMO.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python gotcha of the day

2018-03-15 Thread Python
On Thu, Mar 15, 2018 at 10:21:24AM +0100, Thomas Jollans wrote:
> On 2018-03-15 07:11, Ben Finney wrote:
> > Steven D'Aprano  writes:
> > 
> >> py> """\""
[...]
> Then riddle me this:
> 
> if """\"" is equivalent to "" + "\"" + "" + "", then why isn't
> """ \""" """ equivalent to "" + " \"" + " " + ""?

I've been away on vacation and have deleted a bunch of messages, so
it's likely someone else has already answered this, but if not the
"secret sauce" is that three consecutive quotes are one token, making
the string (or part of it) a triple-quoted string.  That makes the
result of both strings consistent, i.e.:

 """\"" => '"'

 - The first three quotes start the triple-quoted string.
 - The quote after the backslash is escaped, and is part of the string
 - The next three quotes end the triple-quoted string
 - the remaining two quotes yeild the empty string

The version with spaces is completely consistent:

""" \""" """ => ' """ '

 - The first three quotes start the triple-quoted string.
 - They're followed by a space, part of the TQS.
 - The quote after the backslash is escaped, and is part of the string
 - The next TWO quotes do not terminate the TQS, because there are
   not three of them consecutively, thus are part of the TQS.
 - the space is clearly part of the TQS.
 - the remaining three consecutive quotes terminate the TQS.

But the real answer, I think, is:  Just Say No to this in real code...
It's extraordinarily unlikely that you'll have a real-world case that
requires it, and it's extremely difficult to read even in you know
well the relevant rules.  If you found yourself tempted to do this,
there's almost certainly a clearer way to write it, either by reducing
the thing to its result, or by doing string addtion, or what have you.

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


Re: urllib.request.urlopen fails with https

2018-03-15 Thread Ned Deily
On 2018-03-14 18:04, Irv Kalb wrote:
>   File 
> "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py",
>  line 1320, in do_open
> raise URLError(err)
> urllib.error.URLError:  certificate verify failed (_ssl.c:749)>

If you are using Python 3.6 for macOS from a python.org installer, did
you follow the instructions displayed in the installer ReadMe and also
saved at:

/Applications/Python 3.6/ReadMe.rtf

to run the "Install Certificates.command" ?

Either double-click on it in the Finder or, from a shell command line, type:

open "/Applications/Python 3.6/Install Certificates.command"


Certificate verification and OpenSSL

**NEW** This variant of Python 3.6 now includes its own private copy of
OpenSSL 1.0.2.  Unlike previous releases, the deprecated Apple-supplied
OpenSSL libraries are no longer used.  This also means that the trust
certificates in system and user keychains managed by the Keychain Access
application and the security command line utility are no longer used as
defaults by the Python ssl module.  For 3.6.0, a sample command script
is included in /Applications/Python 3.6 to install a curated bundle of
default root certificates from the third-party certifi package
(https://pypi.python.org/pypi/certifi).  If you choose to use certifi,
you should consider subscribing to the project's email update service to
be notified when the certificate bundle is updated.


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


Re: macOS specific - reading calendar information

2018-03-15 Thread Ned Deily
On 2018-03-15 03:58, Christian Gollwitzer wrote:
> Am 15.03.18 um 08:32 schrieb Jan Erik Moström:
>> I would like to read what calendar events I have on a range of days. I
>> would like to get the data from whatever storage Calendar use, in my
>> personal case I sync to iCloud.
[...]
> The native script language is Apple Script or JavaScript. If you want to
> control it from Python, you need a bridge. I have no experience with it,
> but a quick Google search reveals
> https://pypi.python.org/pypi/py-applescript and
> https://docs.python.org/2/library/macosa.html

py-appscript was a great tool but is no longer maintained by its
developer because Apple deprecated much of the interfaces it was built
on.  It still might be useful in this case.

At a lower level, the PyObjC project provides bridging between Python
and Objective C and provides Python wrappers for many macOS system
frameworks, include the CalendarStore framework.

https://pypi.python.org/pypi/pyobjc


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


how do I retry a command only for a specific exception / error

2018-03-15 Thread Ganesh Pal
 import time

from functools import wraps

from qa.utils.easy_popen import run





def retry(ExceptionToCheck, tries=4, delay=5, backoff=2, logger=None):

""" Retry calling the decorated function """

def deco_retry(f):

@wraps(f)

def f_retry(*args, **kwargs):

mtries, mdelay = tries, delay

while mtries > 1:

try:

return f(*args, **kwargs)

except ExceptionToCheck, e:

msg = "%s, Retrying in %d seconds..." % (str(e), mdelay)

if logger:

logger.warning(msg)

else:

print msg

time.sleep(mdelay)

mtries -= 1

mdelay *= backoff

return f(*args, **kwargs)



return f_retry  # true decorator



return deco_retry







@retry(Exception, tries=4, delay=2)

def test_network(text):

try:

 cmd = "ifconfig -a"

stdout, stderr, exit_code = run(cmd, timeout=300)

print stdout, stderr, exit_code

if exit_code != 0:

raise RuntimeError("ERROR (exit_code %d): "

   "\nstdout: %s\nstderr: %s\n" % (exit_code,
stdout, stderr))

except Exception as e:

   print str(e)

   raise Exception("Failed")

print "Success: ", text



test_network("it works!")





All that I  am trying to do here is write a generic function that will
 re-retry
the command  few more times before failing the test



Case 1:  + ve case ( say cmd= ifconfig –a )



gpal-zkj2wrc-1# python  file5.py

vmx0: flags=1008843
metric 0 mtu 1500


options=403bb

ether 00:50:56:90:ef:3d

inet 1.224.39.1 netmask 0x broadcast 1.224.255.255 zone 1

inet6 fe80::250:56ff:fe90:ef3d%vmx0 prefixlen 64 scopeid 0x1 zone 1

inet6 fdfe:9042:c53d:0:250:56ff:fe90:ef3d prefixlen 64 zone 1

nd6 options=21

media: Ethernet 10Gbase-T

status: active

vmx1: flags=8843 metric 0 mtu 1500


options=403bb

ether 00:50:56:90:62:44

inet 10.224.39.1 netmask 0xfc00 broadcast 10.224.39.255 zone 1

nd6 options=29

media: Ethernet 10Gbase-T

status: active



Case 1 : Say I have invalid input  command ( say ifconfig –a ) it will work



gpal-zkj2wrc-1# python  file5.py

 ifconfig: illegal option -- z

usage: ifconfig [-f type:format] [-L] [-C] [-g groupname] interface
address_family

[address [dest_address]] [parameters]

   ifconfig interface create

   ifconfig -a [-L] [-C] [-g groupname] [-d] [-m] [-u] [-v]
[address_family]

   ifconfig -l [-d] [-u] [address_family]

   ifconfig [-L] [-C] [-g groupname] [-d] [-m] [-u] [-v]

1

ERROR (exit_code 1):

stdout:

stderr: ifconfig: illegal option -- z

usage: ifconfig [-f type:format] [-L] [-C] [-g groupname] interface
address_family

[address [dest_address]] [parameters]

   ifconfig interface create

   ifconfig -a [-L] [-C] [-g groupname] [-d] [-m] [-u] [-v]
[address_family]

   ifconfig -l [-d] [-u] [address_family]

   ifconfig [-L] [-C] [-g groupname] [-d] [-m] [-u] [-v]





Failed, Retrying in 2 seconds...

 ifconfig: illegal option -- z

usage: ifconfig [-f type:format] [-L] [-C] [-g groupname] interface
address_family

[address [dest_address]] [parameters]

   ifconfig interface create

   ifconfig -a [-L] [-C] [-g groupname] [-d] [-m] [-u] [-v]
[address_family]

   ifconfig -l [-d] [-u] [address_family]

   ifconfig [-L] [-C] [-g groupname] [-d] [-m] [-u] [-v]

1

ERROR (exit_code 1):

stdout:

stderr: ifconfig: illegal option -- z

usage: ifconfig [-f type:format] [-L] [-C] [-g groupname] interface
address_family

[address [dest_address]] [parameters]

   ifconfig interface create

   ifconfig -a [-L] [-C] [-g groupname] [-d] [-m] [-u] [-v]
[address_family]

   ifconfig -l [-d] [-u] [address_family]

   ifconfig [-L] [-C] [-g groupname] [-d] [-m] [-u] [-v]





Failed, Retrying in 4 seconds...



Case 3:  Assuming my command  threw  an exception say OSError , how do I
retry a command only for a specific exception / error



I am on Python 2.7 and Linux




Regards,
Ganesh Pal
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how do I retry a command only for a specific exception / error

2018-03-15 Thread Steven D'Aprano
On Fri, 16 Mar 2018 11:04:22 +0530, Ganesh Pal wrote:

> All that I  am trying to do here is write a generic function that will
>  re-retry
> the command  few more times before failing the test


Something like this should do it. It gives up immediately on fatal errors 
and tries again on temporary ones. (You have to specify what you consider 
fatal or temporary, of course.) It uses exponential backup to wait longer 
and longer each time you fail, before eventually giving up. 


delay = 2
for attempts in range(max_attempts):
try:
command()
except PermanentFailureError:
raise
except TemporaryFailureError:
sleep(delay)
delay *= 2
else:
break
else:
raise RuntimeError("too many attempts")




-- 
Steve

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