Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Marko Rauhamaa
Steven D'Aprano :

> I applaud you writing different versions of code to try different
> tactics, but you should start from "write the most natural Python code
> you can" *before* you trying guessing what's fast and what's slow.

I'm hard-pressed to imagine a situation where I would write *unnatural*
Python code for performance gains. Choosing a good algorithm applies to
Python programming as well, but convoluted optimization tricks, hardly.

> On Tuesday 22 March 2016 11:49, BartC wrote:
>> No, it passes only a reference to the entire string.
>
> In Python terms, that *is* "the entire string".
>
> The point is, under the hood of the interpreter, *everything* passes
> along references. We rarely draw attention to this fact. Given:
>
> function(1.5, [])
>
> we say "pass the float 1.5 and an empty list to function", not "pass a
> reference to the float 1.5 and a reference to an empty list to a
> reference to the function", because that would get rather annoying
> quickly.

Hm. Annoying to repeat, sure, but I don't know how you could extricate
pointers from Python's abstract data model (or Java's, or Lisp's).
Prolog or a purely functional programming language could get away
without pointers but not Python.

> But that's the critical point: it is *behind the scenes*, an
> implementation detail.

I don't think there is any way to implement, think about or define
Python without pointers.

> In Python code, you don't pass "a reference to" 1.5, you pass 1.5.
> Likewise for all other objects. The abstraction is that you pass
> objects around, not references to objects.

The devil is in the mutables...


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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Mark Lawrence

On 22/03/2016 07:24, Marko Rauhamaa wrote:

Steven D'Aprano :


I applaud you writing different versions of code to try different
tactics, but you should start from "write the most natural Python code
you can" *before* you trying guessing what's fast and what's slow.


I'm hard-pressed to imagine a situation where I would write *unnatural*
Python code for performance gains. Choosing a good algorithm applies to
Python programming as well, but convoluted optimization tricks, hardly.


On Tuesday 22 March 2016 11:49, BartC wrote:

No, it passes only a reference to the entire string.


In Python terms, that *is* "the entire string".

The point is, under the hood of the interpreter, *everything* passes
along references. We rarely draw attention to this fact. Given:

function(1.5, [])

we say "pass the float 1.5 and an empty list to function", not "pass a
reference to the float 1.5 and a reference to an empty list to a
reference to the function", because that would get rather annoying
quickly.


Hm. Annoying to repeat, sure, but I don't know how you could extricate
pointers from Python's abstract data model (or Java's, or Lisp's).
Prolog or a purely functional programming language could get away
without pointers but not Python.


I don't recall seeing any reference to "pointers" above.  In fact, I 
don't ever recall seeing references to pointers in the Python docs. 
There's certainly nothing here 
https://docs.python.org/3/reference/datamodel.html





But that's the critical point: it is *behind the scenes*, an
implementation detail.


I don't think there is any way to implement, think about or define
Python without pointers.


I never think about pointers, I think about objects.  Heck, I wouldn't 
have a clue as to how you go about implementing Jython or IronPython in 
terms of pointers.  I don't even know what anybody could mean by that.





In Python code, you don't pass "a reference to" 1.5, you pass 1.5.
Likewise for all other objects. The abstraction is that you pass
objects around, not references to objects.


The devil is in the mutables...


Whereby these mysterious "pointers" suddenly leap into action I take it?

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: crash while using PyCharm / Python3

2016-03-22 Thread Adam

"Jonathan N. Little"  wrote in message 
news:[email protected]...
> Adam wrote:
>> "Adam"  wrote in message
>> news:[email protected]...
>>>
>>> "Jonathan N. Little"  wrote in message
>>> news:[email protected]...
 Adam wrote:
> There ought to be a way to just reinstall the graphics subsystem 
> rather
> than
> an all-or-none installation approach.

 Yes you can. Did it for a borked install of the nVidia driver. 
 reference
 this:

 
>>>
>>> Thanks, even after doing the following...
>>>
>>> Problem: Need to purge -fglrx
>>>
>>> Typically, the following manual commands will properly uninstall -fglrx:
>>>
>>>   $ sudo apt-get remove --purge xorg-driver-fglrx fglrx*
>>>   $ sudo apt-get install --reinstall libgl1-mesa-glx libgl1-mesa-dri
>>> xserver-xorg-core
>>>   $ sudo dpkg-reconfigure xserver-xorg
>>>
>>> I still get that dreaded "The system is running in low-graphics mode"
>>> error.
>>> And, recovery mode failsafeX and Ctrl+Alt+F1 hangs with the following...
>>>
>>> 
>>> Initializing built-in extension MIT-SCREEN-SAVER
>>> Initializing built-in extension DOUBLE-BUFFER
>>> Initializing built-in extension RECORD
>>> Initializing built-in extension DPMS
>>> Initializing built-in extension Present
>>> Initializing built-in extension DRI3
>>> Initializing built-in extension X-Resource
>>> Initializing built-in extension XVideo
>>> Initializing built-in extension XVideo-MotionCompensation
>>> Initializing built-in extension SELinux
>>> Initializing built-in extension XFree86-VidModeExtension
>>> Initializing built-in extension XFree86-DGA
>>> Initializing built-in extension XFree86-DRI
>>> Initializing built-in extension DRI2
>>> Loading extension GLX
>>> 
>>>
>>
>> After trying the following...
>>
>> http://askubuntu.com/questions/577093/how-to-install-gnome-desktop
>>
>> $ sudo apt-get update
>> $ sudo apt-get install gnome-shell
>>
>>
>> http://tipsonubuntu.com/2014/06/06/change-display-manager-ubuntu-14-04/
>>
>> $ sudo dpkg-reconfigure lightdm
>
> Not sure about ATI, but when you purge the nVidia driver it takes Unity 
> with it so I had to reinstall unity-desktop afterwards. If you want 
> lightdm but are now using gdm, maybe it happened because unity-desktop was 
> uninstalled and you just installed gnome-shell, your can reset:
>
> sudo dpkg-reconfigure gdm
>
> and select lightdm from the list.
>

Thanks, but why fix if it ain't broke?:-)


>
> -- 
> Take care,
>
> Jonathan
> ---
> LITTLE WORKS STUDIO
> http://www.LittleWorksStudio.com 


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


Re: crash while using PyCharm / Python3

2016-03-22 Thread Adam

"Jonathan N. Little"  wrote in message 
news:[email protected]...
> Adam wrote:
>> Sure glad I did not reinstall Ubuntu.  Whew!!
>
> Unless you really-really-really screw things up, you usually do not have 
> to. Linux is not Windows ;-) Even if you had to, with /home on its own 
> partition a reinstall would not have been an issue, you just have to 
> choose the "Something Else" on partitioning and only format the "/" and 
> set the "/home" partition mount point and NOT FORMAT it.

I would have to install additional apps all over again.  Ick!!


>
> A tip: If you use gparted or e2label and give partitions labels. Makes 
> moving partitions and data easier...
>
> sda1 "12.04-root"
> sda5 "old-home"
>
> sdb1 "14.04-root"
> sdb5 "new-home"

Thanks, I'll keep this in mind.


>
> So from a live session when I mount both drives it is easy to keep things 
> straight when I copy my profiles from old drive on sda to new drive with 
> newer version of Ubuntu on sdb...
>
> -- 
> Take care,
>
> Jonathan
> ---
> LITTLE WORKS STUDIO
> http://www.LittleWorksStudio.com 


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


Re: Using SSL socket as stdin for subprocess.Popen

2016-03-22 Thread dieter
Matt Ruffalo  writes:
> ...
> I've been using SSL for the communication between the client and server,
> ...
> I've hit an issue that I'm not sure how to work through, though. I'm
> attempting to use a SSL socket (and/or the result of its 'makefile'
> method) directly as the `stdin` argument to subprocess.Popen, but it
> seems that the *encrypted* data is used by the subprocess.

In order to access an SSL socket, something special must be done
during the connection(/opening) phase: then certificates are
exchanged/verified and a common session key is created (used
to encrypt the exchanged data). Only after this special handling
it the SSL socket transparent.

Your observation indicates that your socket is not opened
in this special SSL way - thus, you get the raw data.

Likely, you must make sure that proper SSL initialization has taken
place before you hand the socket down as "stdin" to your "subprocess.Popen".

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


error sintax

2016-03-22 Thread Gabriel Forcarelli dos Santos
meu python não esta reconhecendo os sinais de calculos em geral, peço a
ajuda de vocês.
-- 
https://mail.python.org/mailman/listinfo/python-list


Why I got handshake failure when passing specific ciphers to wrap_socket?

2016-03-22 Thread TwoThree Tee
I tried two kinds of ciphers "kRSA, aRSA, RSA" and "kDHE, kEDH, DH". The
later failed with handshake failure alert (observed from packet dump). For
the successful one, the chosen cipher suite is DHE-RSA-AES256-SHA which is
also included in the Client Hello message of the failed case. That's what
confused me. Since I have provided the supported cipher suite why the
handshake failed? I also tried the cipher with openssl: openssl s_client
-connect ebay.com:443 -cipher "kDHE, kEDH, DH" -tls1, and it works well.
Any idea to troubleshoot? Thanks.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Static caching property

2016-03-22 Thread dieter
"Joseph L. Casale"  writes:
> ...
> I need to cache the results of a method on a class across all instances.

If a method call on any instance defines the return value for
all instances, then this method likely should be a class method --
and use a class attribute to store the result -- something like this:

class C(object):

_cache = {}

@classmethod
def f(cls, ...):
  ... determine cache key `key` ...
  v = cls._cache.get(key)
  if v is None:
 v = cls._cache[key] = ...
  return v

It will work also without the "@classmethod".

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


Re: error sintax

2016-03-22 Thread anantguptadbl
On Tuesday, March 22, 2016 at 1:58:30 PM UTC+5:30, Gabriel Forcarelli dos 
Santos wrote:
> meu python não esta reconhecendo os sinais de calculos em geral, peço a
> ajuda de vocês.

Hi Gabriel,

Can you give some details

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


Re: GAPI -- Sharing a post to Social Networking Pages from my App

2016-03-22 Thread Karthik Reddy
On Tuesday, March 22, 2016 at 9:54:53 AM UTC+5:30, Mark Lawrence wrote:
> On 22/03/2016 04:14, Karthik Reddy wrote:
> > Hi Experts,
> >
> > I am trying to post on facebook and google plus  page  from my application. 
> > I am using facebook-sdk an d I am able to post using local machine but I am 
> > not able to post from dev server.
> >
> > Can Anyone Please help me on this.
> >
> > Thanks,
> > Karthik
> >
> 
> Please state your OS and Python version, the code that you've tried and 
> exactly what went wrong, including the full traceback if there is one.
> 
> -- 
> My fellow Pythonistas, ask not what our language can do for you, ask
> what you can do for our language.
> 
> Mark Lawrence

Hi Lawrence Thank you for your quick reply  .I am using Ubuntu 14.04 and python 
2.7.6 version.


In Template I have written


publish


{% block google_script %}

window.___gcfg = {
lang: 'en',
parsetags: 'onload',
isSignedOut: true
};

// var sour =  document.getElementById("1");
// // console.log(sour)
// var idd=document.getElementById("1").id;
// console.log(idd)
function(){ window.open = $("#sharePost").click(); };


https://apis.google.com/js/platform.js"; async defer>
{% endblock %}

{% block share %}


  var options = {
contenturl: 'http://localhost:8000',
clientid: 'X.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
prefilltext: 'New project is added',
calltoactionurl : 'https://plus.google.com/u/0/112729364286841783635/posts' 
   
  };
  // Call the render method when appropriate within your app to display
  // the button.
  gapi.interactivepost.render('sharePost', options);
  console.log(new Error().stack);

{% endblock %}

{% block google_style %}

iframe[src^="https://apis.google.com/u/0/_/widget/oauthflow/toast";] {
display: none;
}

{% endblock %}


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


Re: GAPI -- Sharing a post to Social Networking Pages from my App

2016-03-22 Thread Karthik Reddy
On Tuesday, March 22, 2016 at 9:54:53 AM UTC+5:30, Mark Lawrence wrote:
> On 22/03/2016 04:14, Karthik Reddy wrote:
> > Hi Experts,
> >
> > I am trying to post on facebook and google plus  page  from my application. 
> > I am using facebook-sdk an d I am able to post using local machine but I am 
> > not able to post from dev server.
> >
> > Can Anyone Please help me on this.
> >
> > Thanks,
> > Karthik
> >
> 
> Please state your OS and Python version, the code that you've tried and 
> exactly what went wrong, including the full traceback if there is one.
> 
> -- 
> My fellow Pythonistas, ask not what our language can do for you, ask
> what you can do for our language.
> 
> Mark Lawrence

The error I am getting is "Uncaught ReferenceError: gapi is not defined"
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Convert list to another form but providing same information

2016-03-22 Thread Steven D'Aprano
On Tue, 22 Mar 2016 12:35 pm, Paul Rubin wrote:

> Maurice  writes:
>> I have a list such [6,19,19,21,21,21]
>> Therefore the resulting list should be:
>> [0,0,0,0,0,0,1,0,0,0...,2,0,3,0...0]
> 
> Rather than a sparse list you'd typically want a dictionary (untested):
> 
>   from collections import defaultdict
>   the_list = [0,0,0,0,0,0,1,0,0,0...,2,0,3,0...0]
>   ...
>   days = defaultdict(int)
>   for t in the_list:
>  days[t] += 1
> 
> this results in days being the defaultdict { 6:1, 19:2, 21:3 }.

For just 3 items out of 32, doing this as an optimisation is barely worth
it. Using Python 3.4, I get 168 bytes for the list solution and 152 bytes
for a default dict solution:

py> print(days)
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0]
py> sys.getsizeof(days)
168

py> from collections import defaultdict
py> d = defaultdict(int)
py> d.update({ 6:1, 19:2, 21:3 })
py> sys.getsizeof(d)
152

By all means use whichever solution suits you best, but don't expect to save
much memory in a "spare array" of only 32 items :-)



-- 
Steven

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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread BartC

On 22/03/2016 01:01, Steven D'Aprano wrote:

On Tue, 22 Mar 2016 06:43 am, BartC wrote:


This code was adapted from a program that used:

 readstrfile(filename)

which either returned the contents of the file as a string, or 0.


What an interesting function. And I don't mean that in a good way.

So if it returns 0, how do you know what the problem is? Mistyped file name?
Permission denied? File doesn't actually exist? Disk corruption and you
can't open the file? Some weird OS problem where you can't *close* the
file? (That can actually happen, although it's never happened to me.) How
do you debug any problems, given only "0" as a result?

What happens if you read (let's say) a 20GB Blue-Ray disk image?


I think you're making far too much of a throwaway function to grab a 
file off disk and into memory.


But out of interest, how would /you/ write a function that takes a 
file-spec and turns it into an in-memory string? And what would its use 
look like?



Pythonic code probably uses a lot of iterables:

for value in something:
 ...



in preference to Pascal code written in Python:

for index in range(len(something)):
 value = something[index]


(Suppose you need both the value and its index in the loop? Then the 
one-line for above won't work. For example, 'something' is [10,20,30] 
and you want to print:


 0: 10
 1: 20
 2: 30 )


 ...
or worse:

index = 0
while index < len(something):
 value = something[index]
 ...
 index += 1



(I don't know where that while-loop idiom comes from. C? Assembly? Penitent
monks living in hair shirts in the desert and flogging themselves with
chains every single night to mortify the accursed flesh? But I'm seeing it
a lot in code written by beginners. I presume somebody, or some book, is
teaching it to them. "Learn Python The Hard Way" perhaps?)


Are you suggesting 'while' is not needed? Not everything fits into a 
for-loop you know! Why, take my own readtoken() function:


  symbol = anything_other_than_skip_sym

  while symbol != skip_sym:
 symbol = readnextsymbol()

Of course, a repeat-until or repeat-while would suit this better (but I 
don't know how it fits into Python syntax). So there's a case here for 
increasing the number of loop statements not reducing them.



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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Chris Angelico
On Tue, Mar 22, 2016 at 10:05 PM, BartC  wrote:
> But out of interest, how would /you/ write a function that takes a file-spec
> and turns it into an in-memory string? And what would its use look like?

def read_file(fn, *a, **kw):
with open(fn, *a, **kw) as f:
return f.read()

Usage:

script = read_file(".bashrc")
data = read_file("Ellalune_AlicePortrait.jpg", "rb")
decoded = read_file("greek.srt", encoding="ISO-8859-7")

If there's any problem with reading the file, an exception will be
raised. Also, thanks to the 'with' block, I'm guaranteed that the file
will have been closed before read_file() returns, which means I can
immediately go and write to the file without a conflict.

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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Rustom Mody
On Tuesday, March 22, 2016 at 7:32:13 AM UTC+5:30, Mark Lawrence wrote:
> On 22/03/2016 00:49, BartC wrote:
> >
> > I was surprised at one time that slices don't create 'views', but I've
> > since implemented view-slices and I can appreciate the problems.)
> >
> 
> Why, the docs are quite clear on how Python works?  Of course you can 
> always use memoryviews 
> https://docs.python.org/3/library/stdtypes.html#typememoryview

Interesting!
Can you show/point me to a recipe for getting a copyless view of any arbitrary 
(not necessarily byte) array?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: GAPI -- Sharing a post to Social Networking Pages from my App

2016-03-22 Thread Steven D'Aprano
On Tue, 22 Mar 2016 09:37 pm, Karthik Reddy wrote:

> The error I am getting is "Uncaught ReferenceError: gapi is not defined"


Have you tried googling for it? That's a Javascript error:

https://duckduckgo.com/html/?q=uncaught+reference+error+gapi+is+not+defined



-- 
Steven

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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Ned Batchelder
On Tuesday, March 22, 2016 at 7:05:20 AM UTC-4, BartC wrote:
> On 22/03/2016 01:01, Steven D'Aprano wrote:
> > Pythonic code probably uses a lot of iterables:
> >
> > for value in something:
> >  ...
> 
> > in preference to Pascal code written in Python:
> >
> > for index in range(len(something)):
> >  value = something[index]
> 
> (Suppose you need both the value and its index in the loop? Then the 
> one-line for above won't work. For example, 'something' is [10,20,30] 
> and you want to print:
> 
>   0: 10
>   1: 20
>   2: 30 )

Then you use enumerate:

for index, value in enumerate(something):
print("{}: {}".format(index, value))

Python has a number of iteration features that you don't find in other
languages.  You might find this introduction to them helpful:

Loop Like a Native: http://nedbatchelder.com/text/iter.html

> 
> >  ...
> > or worse:
> >
> > index = 0
> > while index < len(something):
> >  value = something[index]
> >  ...
> >  index += 1
> 
> > (I don't know where that while-loop idiom comes from. C? Assembly? Penitent
> > monks living in hair shirts in the desert and flogging themselves with
> > chains every single night to mortify the accursed flesh? But I'm seeing it
> > a lot in code written by beginners. I presume somebody, or some book, is
> > teaching it to them. "Learn Python The Hard Way" perhaps?)
> 
> Are you suggesting 'while' is not needed? Not everything fits into a 
> for-loop you know!

Steven wasn't saying 'while' is not needed. He was wondering about the
idiom of manually maintaining an integer count of the number of times
around a while loop ("I don't know where *that* while-loop idiom comes from").

While-loops are still useful in Python, but for-loops are much more common.

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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Ian Foote



On 22/03/16 11:05, BartC wrote:

On 22/03/2016 01:01, Steven D'Aprano wrote:


Pythonic code probably uses a lot of iterables:

for value in something:
 ...



in preference to Pascal code written in Python:

for index in range(len(something)):
 value = something[index]


(Suppose you need both the value and its index in the loop? Then the 
one-line for above won't work. For example, 'something' is [10,20,30] 
and you want to print:


 0: 10
 1: 20
 2: 30 )



The builtin enumerate function is the idiomatic way:

for index, item in enumerate(something):
...

Regards,
Ian F
--
https://mail.python.org/mailman/listinfo/python-list


Re: GAPI -- Sharing a post to Social Networking Pages from my App

2016-03-22 Thread Karthik Reddy
On Tuesday, March 22, 2016 at 4:48:37 PM UTC+5:30, Steven D'Aprano wrote:
> On Tue, 22 Mar 2016 09:37 pm, Karthik Reddy wrote:
> 
> > The error I am getting is "Uncaught ReferenceError: gapi is not defined"
> 
> 
> Have you tried googling for it? That's a Javascript error:
> 
> https://duckduckgo.com/html/?q=uncaught+reference+error+gapi+is+not+defined
> 
> 
> 
> -- 
> Steven
Yup I googled it I am not getting where I need to modify
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: GAPI -- Sharing a post to Social Networking Pages from my App

2016-03-22 Thread Karthik Reddy
On Tuesday, March 22, 2016 at 4:55:40 PM UTC+5:30, Karthik Reddy wrote:
> On Tuesday, March 22, 2016 at 4:48:37 PM UTC+5:30, Steven D'Aprano wrote:
> > On Tue, 22 Mar 2016 09:37 pm, Karthik Reddy wrote:
> > 
> > > The error I am getting is "Uncaught ReferenceError: gapi is not defined"
> > 
> > 
> > Have you tried googling for it? That's a Javascript error:
> > 
> > https://duckduckgo.com/html/?q=uncaught+reference+error+gapi+is+not+defined
> > 
> > 
> > 
> > -- 
> > Steven
> Yup I googled it I am not getting where I need to modify

Is my approach is correct or if not Is there any other approach 

Please help me with this.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Chris Angelico
On Tue, Mar 22, 2016 at 10:45 PM, Dennis Lee Bieber
 wrote:
> On Tue, 22 Mar 2016 11:05:01 +, BartC  declaimed the
> following:
>
>>
>>But out of interest, how would /you/ write a function that takes a
>>file-spec and turns it into an in-memory string? And what would its use
>>look like?
>>
> At the basics -- and letting the garbage collector get the file handle
> later...
>
> imstr = open(fileName, "r").read()
>
> If you want a separate function... (the name here stinks, but...)
>
> def fn2str(fileName):
> fin = open(fileName, "r")
> imstr = fin.read()
> fin.close()
> return imstr
>
> ...
> data = fn2str("some.file")
>
> letting any exceptions propagate upwards.

While we're on the subject of Pythonic ways to read files, this is NOT.

http://thedailywtf.com/articles/finding-the-file

It's also not idiomatic C# code either, though...

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


Re: monkey patching __code__

2016-03-22 Thread Sven R. Kunze

On 21.03.2016 21:42, Matt Wheeler wrote:

On 20 March 2016 at 16:46, Sven R. Kunze  wrote:

On 19.03.2016 00:58, Matt Wheeler wrote:

I know you have a working solution now with updating the code &
defaults of the function, but what about just injecting your function
into the modules that had already imported it after the
monkeypatching?

Seems perhaps cleaner, unless you'd end up having to do it to lots of
modules...

Why do you consider it cleaner?

I think it would be more explicit and understandable for someone
reading your code.

I suppose it's quite subjective :)


As far as I can see, the code replacement approach solves the problem 
once and for all. Thus is far more stable.


Manually finding out every single module that might or might not have 
imported "reverse" before we could monkeypatch it might result in a 
maintenance nightmare (just think about a Django upgrade).



It reminds me of list replacement:

mylist = newlist
mylist[:] = newlist

The latter keeps the reference stable whereas the former does not. Same 
with monkeypatching.



Best,
Sven
--
https://mail.python.org/mailman/listinfo/python-list


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Steven D'Aprano
On Tue, 22 Mar 2016 10:05 pm, BartC wrote:

> On 22/03/2016 01:01, Steven D'Aprano wrote:
>> On Tue, 22 Mar 2016 06:43 am, BartC wrote:
>>
>>> This code was adapted from a program that used:
>>>
>>>  readstrfile(filename)
>>>
>>> which either returned the contents of the file as a string, or 0.
>>
>> What an interesting function. And I don't mean that in a good way.
>>
>> So if it returns 0, how do you know what the problem is? Mistyped file
>> name? Permission denied? File doesn't actually exist? Disk corruption and
>> you can't open the file? Some weird OS problem where you can't *close*
>> the file? (That can actually happen, although it's never happened to me.)
>> How do you debug any problems, given only "0" as a result?
>>
>> What happens if you read (let's say) a 20GB Blue-Ray disk image?
> 
> I think you're making far too much of a throwaway function to grab a
> file off disk and into memory.
> 
> But out of interest, how would /you/ write a function that takes a
> file-spec and turns it into an in-memory string? And what would its use
> look like?

I already told you. For a quick and dirty script where I didn't care much
about reliability, I would use:

the_text = open(filename).read()

and leave it at that.

There's a hierarchy of less- to more-reliable. Next would be:

with open(filename) as f:
the_text = f.read()

which guarantees to close the file promptly. Better still would be to avoid
dealing with the entire file in one (potentially enormous) chunk, and
process it line by line:

with open(filename) as f:
for line in f:
process line


If for some reason I *had* to process it as one big chunk of text, where I
knew that there was a chance that it could be bigger than what I could
comfortably hold in memory in one go, I would research mmap. But I don't
really know anything about how that works. I've been lucky enough to never
need to care.

Dealing with out-of-memory errors on modern OSes is one of the hardest
things to get right. In some ways, we're lucky, because the OS will try
really hard to give the illusion that you have an infinite amount of
memory. But the illusion is never perfect, and the abstraction of "virtual
memory plus real memory = infinite memory" can break down. I once foolishly
tried to create an *enormous* list, something like [0]*10**100, and my OS
very kindly started swapping applications in and out of memory trying to
free up 40 000 000 billion billion billion billion billion billion billion
billion billion petabytes of memory (estimated).

Not only did Python lock up, but so did the OS. I decided to leave it
overnight to see if it would recover, but 16 hours later it was still
locked up and frantically trying to swap memory. I'm not sure why the
OOM-Killer didn't trigger. I ended up having to do a hard power-down to
recover. So virtual memory is a mixed blessing.


>> Pythonic code probably uses a lot of iterables:
>>
>> for value in something:
>>  ...
> 
>> in preference to Pascal code written in Python:
>>
>> for index in range(len(something)):
>>  value = something[index]
> 
> (Suppose you need both the value and its index in the loop? Then the
> one-line for above won't work. For example, 'something' is [10,20,30] 
> and you want to print:
> 
>   0: 10
>   1: 20
>   2: 30 )



for index, n in enumerate([10, 20, 30]):
print(index, ":", n)


>> or worse:
>>
>> index = 0
>> while index < len(something):
>>  value = something[index]
>>  ...
>>  index += 1
> 
>> (I don't know where that while-loop idiom comes from. C? Assembly?
>> Penitent monks living in hair shirts in the desert and flogging
>> themselves with chains every single night to mortify the accursed flesh?
>> But I'm seeing it a lot in code written by beginners. I presume somebody,
>> or some book, is teaching it to them. "Learn Python The Hard Way"
>> perhaps?)
> 
> Are you suggesting 'while' is not needed? 

Of course not. Use while loops for when you need a while loop.

But *writing a for-loop using while* is an abuse of while.



-- 
Steven

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


RE: Static caching property

2016-03-22 Thread Joseph L. Casale
> If a method call on any instance defines the return value for
> all instances, then this method likely should be a class method --
> and use a class attribute to store the result -- something like this:
>
> class C(object):
>
> _cache = {}
>
> @classmethod
> def f(cls, ...):
>   ... determine cache key `key` ...
>   v = cls._cache.get(key)
>   if v is None:
>  v = cls._cache[key] = ...
>   return v
>
> It will work also without the "@classmethod".

Ok, classmethod has advantages when considering OOP, but this is flawed.

Ethan was spot on (aside from the typo in the return statement), if the 
expensive
API call returns None, since it is a singleton your code will continue to 
invoke it.

This implementation also invokes additional hashing and lookups.

Ethan's implementation also supports inheritance.

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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Steven D'Aprano
On Tue, 22 Mar 2016 10:55 pm, Chris Angelico wrote:

> While we're on the subject of Pythonic ways to read files, this is NOT.
> 
> http://thedailywtf.com/articles/finding-the-file
> 
> It's also not idiomatic C# code either, though...

Obviously not. They should have used a switch.

I like the comment from "PWolff":

A loop might be faster to write (for a human) and easier 
to maintain, but it takes significantly longer to run. 
(Several ppm in this case, I assume.)

(PPM? Parts per million?)

Unless PWolff is being too-ironic-by-half, I expect to see his work featured
on The Daily WTF soon.


I like this one:

http://thedailywtf.com/articles/string-cheese



-- 
Steven

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


Re: need help With understanding

2016-03-22 Thread Bob Gailer
On Mar 21, 2016 5:40 PM, "Peter Pearson"  wrote:
>
> On Mon, 21 Mar 2016 11:18:57 +, mohamed mohamud wrote:
> > hey im new at Learning Python, and i have an issue which i would like
> > som help With.
> >
> > i have currently installed Python, and im Reading this book which
> > tells me i have to have IDLE, but i cant find it on my computer. do i
> > need to install it? and if so where do/can i find it.?
>
I believe IDLE is part of the Python distribution. Do a search for idle
from the python directory.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Jussi Piitulainen
BartC writes:

> Not everything fits into a for-loop you know! Why, take my own
> readtoken() function:
>
>   symbol = anything_other_than_skip_sym
>
>   while symbol != skip_sym:
>  symbol = readnextsymbol()
>
> Of course, a repeat-until or repeat-while would suit this better (but
> I don't know how it fits into Python syntax). So there's a case here
> for increasing the number of loop statements not reducing them.

Not sure why nobody seems to respond to this part. Perhaps I just missed
it? It's true that while has its uses, or at least I think I've used it
in Python once or twice. But there's more fun to be had by turning your
data into a stream-like object.

stream = iter('   /* this is C! */') # <-- produces a character at a time

Now you can ask for the next item that satisfies a condition using a
generator expression:

next(symbol for symbol in stream if not symbol.isspace())
---> '/'

next(symbol for symbol in stream if not symbol.isspace())
---> '*'

Or collect the remaining items:

list(symbol for symbol in stream if not symbol.isspace())
---> ['t', 'h', 'i', 's', 'i', 's', 'C', '!', '*', '/']

You could also say:

for symbol in stream:
   if symbol.isspace(): continue
   ...

But this particular stream is empty by now. I work with long streams of
tokenized and annotated sentences (which for me are streams of tokens)
that sometimes come packed in streams of paragraphs packed in streams of
texts. I build whatever stream I happen to want by nesting generator
functions and generator expressions and some related machinery. (You
could build on a character stream or a byte stream that you obtain by
opening a file for reading; I tend to read line by line through
itertools.groupby, because that's what I do.)

These things compose well.
-- 
https://mail.python.org/mailman/listinfo/python-list


exec inside functions in Python 3

2016-03-22 Thread Steven D'Aprano
Anyone have any idea what is going on here?


def test():
spam = 1
exec("spam = 2; print('inside exec: %d' % spam)")
print('outside exec: %d' % spam)


In Python 2.7:

py> test()
inside exec: 2
outside exec: 2



In Python 3.4:

outside exec: 1
py> test()
inside exec: 2
outside exec: 1



What happened to spam?



-- 
Steven

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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread BartC

On 22/03/2016 11:15, Chris Angelico wrote:

On Tue, Mar 22, 2016 at 10:05 PM, BartC  wrote:

But out of interest, how would /you/ write a function that takes a file-spec
and turns it into an in-memory string? And what would its use look like?


def read_file(fn, *a, **kw):
 with open(fn, *a, **kw) as f:
 return f.read()

Usage:

script = read_file(".bashrc")
data = read_file("Ellalune_AlicePortrait.jpg", "rb")
decoded = read_file("greek.srt", encoding="ISO-8859-7")

If there's any problem with reading the file, an exception will be
raised. Also, thanks to the 'with' block, I'm guaranteed that the file
will have been closed before read_file() returns, which means I can
immediately go and write to the file without a conflict.



I'm not sure I follow. Your solution to dealing with the scenarios 
raised by Steven D'Aprano is to:


(1) Not bother with exceptions at all inside the function

(2) Not bother with them in the user code either

(3) Let any errors just crash out (raise a Python system error) (just 
like I did in my original jpeg program which I was called out on)


(4) Or if the user code does want to check for certain errors (like, 
File Not Found, by far the most likely, and so that it can deal with 
that and continue executing), it now has to go and dig out docs for ... 
what? The user code needs to know what is going on inside the supposedly 
opaque function it's calling.


--
Bartc

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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Chris Angelico
On Tue, Mar 22, 2016 at 11:52 PM, Jussi Piitulainen
 wrote:
> Now you can ask for the next item that satisfies a condition using a
> generator expression:
>
> next(symbol for symbol in stream if not symbol.isspace())
> ---> '/'
>
> next(symbol for symbol in stream if not symbol.isspace())
> ---> '*'

Or use filter(), which is sometimes clearer:

# You probably want a more sophisticated function here
def nonspace(ch): return not ch.isspace()

next(filter(nonspace, stream))

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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Chris Angelico
On Tue, Mar 22, 2016 at 11:59 PM, BartC  wrote:
> (1) Not bother with exceptions at all inside the function
>
> (2) Not bother with them in the user code either
>
> (3) Let any errors just crash out (raise a Python system error) (just like I
> did in my original jpeg program which I was called out on)
>
> (4) Or if the user code does want to check for certain errors (like, File
> Not Found, by far the most likely, and so that it can deal with that and
> continue executing), it now has to go and dig out docs for ... what? The
> user code needs to know what is going on inside the supposedly opaque
> function it's calling.

Yes, yes, at first, and try it.

The first step in any program is to write it in the very simplest way
possible. That usually means ignoring all error handling. And yes,
this is true in EVERY language - C, PHP, Pike, DeScribe Macro
Language, you name it. Then you try it, and you find one of two
things:

1) The code you've written is encountering error conditions that it
can't handle, and has to pass upstream; or
2) The code you've written is getting passed error conditions that it
knows how to deal with.

The first one is a time to raise an exception. The second is a time to
catch one. And since, by default, Python prints those exceptions to
the console, you should [1] have all the information you need to catch
the ones you understand, because you've seen them in testing.

Note, though, that "deal with" really means "deal with", and NOT
"print oops to the console and terminate". If all you're going to do
with an exception is print and terminate, *let it go*, unless it's a
user-triggered failure, in which case you catch it right at the very
highest level, and basically fall off the end of your program. The
number of times you have sys.exit() in an except clause should be
vanishingly small.

ChrisA

[1] Some libraries force you to dig around a bit to figure out how
you're supposed to import those exception classes. But that's usually
*one* thing to look up in the docs - "oh, so I import
foobarbletch.exceptions.OutOfBeerException".
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: crash while using PyCharm / Python3

2016-03-22 Thread Jonathan N. Little

Adam wrote:

Thanks, but why fix if it ain't broke?:-)


No reason to.

--
Take care,

Jonathan
---
LITTLE WORKS STUDIO
http://www.LittleWorksStudio.com
--
https://mail.python.org/mailman/listinfo/python-list


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Jussi Piitulainen
Chris Angelico writes:

> On Tue, Mar 22, 2016 at 11:52 PM, Jussi Piitulainen wrote:
>> Now you can ask for the next item that satisfies a condition using a
>> generator expression:
>>
>> next(symbol for symbol in stream if not symbol.isspace())
>> ---> '/'
>>
>> next(symbol for symbol in stream if not symbol.isspace())
>> ---> '*'
>
> Or use filter(), which is sometimes clearer:
>
> # You probably want a more sophisticated function here
> def nonspace(ch): return not ch.isspace()
>
> next(filter(nonspace, stream))

Sure.

# But there's more fun hiding in the standard library.
next(itertools.filterfalse(operator.methodcaller('isspace'), stream))
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Chris Angelico
On Wed, Mar 23, 2016 at 12:15 AM, Jussi Piitulainen
 wrote:
> Chris Angelico writes:
>
>> On Tue, Mar 22, 2016 at 11:52 PM, Jussi Piitulainen wrote:
>>> Now you can ask for the next item that satisfies a condition using a
>>> generator expression:
>>>
>>> next(symbol for symbol in stream if not symbol.isspace())
>>> ---> '/'
>>>
>>> next(symbol for symbol in stream if not symbol.isspace())
>>> ---> '*'
>>
>> Or use filter(), which is sometimes clearer:
>>
>> # You probably want a more sophisticated function here
>> def nonspace(ch): return not ch.isspace()
>>
>> next(filter(nonspace, stream))
>
> Sure.
>
> # But there's more fun hiding in the standard library.
> next(itertools.filterfalse(operator.methodcaller('isspace'), stream))

... at that point, the genexp is miles ahead in readability :)

Although I do sometimes yearn for a "filterout" function that does the
same thing as filter() but negates its predicate. Then you could use:

next(filterout(str.isspace, stream))

to say "give me the next from the stream, filtering out those which
are spaces". It's not hard to write, of course.

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


Re: Static caching property

2016-03-22 Thread Ian Kelly
On Mon, Mar 21, 2016 at 6:05 PM, Steven D'Aprano  wrote:
> On Tue, 22 Mar 2016 04:48 am, Ian Kelly wrote:
>
>> You don't actually need a metaclass for this:
>>
> class Desc:
>> ... def __get__(self, obj, type=None):
>> ... if not type._cached_value:
>> ... type._cached_value = compute_value(type)
>> ... return type._cached_value
>
>
> This won't quite work. What if the cached value happens to be falsey, yet
> still expensive to compute? You should compare it to a known sentinel which
> the expensive function will never return (possibly None). Or use a hasattr
> test: if not hasattr(type, '_cached_value').

Sure. This was just a quick-and-dirty demonstration that I threw
together in 30 seconds.

> Also, you don't need the default type=None. The descriptor protocol should
> never call __get__ without supplying the type. The obj may be None, but I
> don't believe there are any circumstances where type will be None.

Why do the examples in the Python docs use type=None? I literally just
copy-pasted the method signature from there, since I can never
remember which argument comes first.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: exec inside functions in Python 3

2016-03-22 Thread Chris Angelico
On Tue, Mar 22, 2016 at 11:57 PM, Steven D'Aprano  wrote:
> Anyone have any idea what is going on here?
>
>
> def test():
> spam = 1
> exec("spam = 2; print('inside exec: %d' % spam)")
> print('outside exec: %d' % spam)
>
>
> In Python 2.7:
>
> py> test()
> inside exec: 2
> outside exec: 2
>
>
>
> In Python 3.4:
>
> outside exec: 1
> py> test()
> inside exec: 2
> outside exec: 1
>
>
>
> What happened to spam?

In Python 2, exec is magical. In Python 3, it's a function like any
other, so it doesn't have access to local variables; what it gets is
locals(), which is a one-way representation of current locals -
changes don't propagate back.

It'd maybe be nice to be able to tell Python to compile a function
with a "real locals dictionary", which would then be mutated by
locals() changes (as locals() would simply return it as-is). That'd
fix this "problem", if problem it indeed is.

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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Jussi Piitulainen
Chris Angelico writes:

> On Wed, Mar 23, 2016 at 12:15 AM, Jussi Piitulainen wrote:
>> Chris Angelico writes:
>>
>>> Or use filter(), which is sometimes clearer:
>>>
>>> # You probably want a more sophisticated function here
>>> def nonspace(ch): return not ch.isspace()
>>>
>>> next(filter(nonspace, stream))
>>
>> Sure.
>>
>> # But there's more fun hiding in the standard library.
>> next(itertools.filterfalse(operator.methodcaller('isspace'), stream))
>
> ... at that point, the genexp is miles ahead in readability :)

;)

> Although I do sometimes yearn for a "filterout" function that does the
> same thing as filter() but negates its predicate. Then you could use:
>
> next(filterout(str.isspace, stream))
>
> to say "give me the next from the stream, filtering out those which
> are spaces". It's not hard to write, of course.

from itertools import filterfalse as filterout

next(filterout(str.isspace, """

 I didn't know str.isspace works like that!

"""))
---> 'I'
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Chris Angelico
On Wed, Mar 23, 2016 at 12:32 AM, Jussi Piitulainen
 wrote:
>> Although I do sometimes yearn for a "filterout" function that does the
>> same thing as filter() but negates its predicate. Then you could use:
>>
>> next(filterout(str.isspace, stream))
>>
>> to say "give me the next from the stream, filtering out those which
>> are spaces". It's not hard to write, of course.
>
> from itertools import filterfalse as filterout
>
> next(filterout(str.isspace, """
>
>  I didn't know str.isspace works like that!
>
> """))
> ---> 'I'

str.isspace(s) <-> s.isspace(), as long as type(s) is str. Very handy
for this sort of thing. And yeah, the import is an option, but if I'm
trying to explain stuff to people, it's usually easier to grab a
genexp (full flexibility, but the complexity) than to play around with
importing. When the function you want exists and returns true for the
things you want, filter() has a big win; for any other situation, it's
not worth reaching to itertools for a specific solution when the
generic one will cover this and every other case.

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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Jussi Piitulainen
Chris Angelico writes:

> And yeah, the import is an option, but if I'm trying to explain stuff
> to people, it's usually easier to grab a genexp (full flexibility, but
> the complexity) than to play around with importing. When the function
> you want exists and returns true for the things you want, filter() has
> a big win; for any other situation, it's not worth reaching to
> itertools for a specific solution when the generic one will cover this
> and every other case.

True. Filtering is so simple.

The big win for me has been itertools.groupby. The other stuff I mostly
play with for amusement. But hey, nothing frivolous in amusement!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Jon Ribbens
On 2016-03-22, Chris Angelico  wrote:
> The first step in any program is to write it in the very simplest way
> possible. That usually means ignoring all error handling. And yes,
> this is true in EVERY language - C, PHP, Pike, DeScribe Macro
> Language, you name it.

I'm afraid I have to say I think this is absolutely terrible advice.
If you write code in a language that does not have exceptions (e.g. C)
and get it working with no error handling, the chances are
approximately 100% that it will stay that way and be shipped without
error handling, until that lack causes someone a major problem.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Chris Angelico
On Wed, Mar 23, 2016 at 12:46 AM, Jon Ribbens
 wrote:
> On 2016-03-22, Chris Angelico  wrote:
>> The first step in any program is to write it in the very simplest way
>> possible. That usually means ignoring all error handling. And yes,
>> this is true in EVERY language - C, PHP, Pike, DeScribe Macro
>> Language, you name it.
>
> I'm afraid I have to say I think this is absolutely terrible advice.
> If you write code in a language that does not have exceptions (e.g. C)
> and get it working with no error handling, the chances are
> approximately 100% that it will stay that way and be shipped without
> error handling, until that lack causes someone a major problem.

There are languages in which it's inadvisable. But can you honestly
say that you've never written a C program with even a single error
check omitted, first time? (The trivial case of having never written a
C program counts only because smart people leave C to other people.)
And PHP's strpos function is not an abomination because it's
impossible to distinguish FALSE from 0, but because *most* PHP
programs are written without the mandatory check for FALSE after every
strpos. So yes, it does happen, a lot. The difference with languages
like Python is that this actually *is* good advice in Python. Due to a
mistake in editing, the parentheses around the "true in EVERY
language" sentence were lost, which would have made it clearer that
this is in two distinct parts:

1) This IS what happens, whatever language you use
2) This is the right thing to do in Python, but not always elsewhere.

My apologies for the confusion.

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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread BartC

On 22/03/2016 13:13, Chris Angelico wrote:

On Tue, Mar 22, 2016 at 11:59 PM, BartC  wrote:



The first step in any program is to write it in the very simplest way
possible. That usually means ignoring all error handling. And yes,
this is true in EVERY language - C, PHP, Pike, DeScribe Macro
Language, you name it. Then you try it, and you find one of two
things:


(Not in C; you can cause serious damage! But when I tried that approach 
in my experimental Python programs, it wasn't popular, I recall.)



Note, though, that "deal with" really means "deal with", and NOT
"print oops to the console and terminate". If all you're going to do
with an exception is print and terminate, *let it go*, unless it's a
user-triggered failure, in which case you catch it right at the very
highest level, and basically fall off the end of your program. The
number of times you have sys.exit() in an except clause should be
vanishingly small.


So code like the following is consigned to history?

 while 1:
 |   file = input ("Filename (press enter to quit)? ")
 |   if file == "": break
 |   print ("Trying to open:",file,"...")
 |   s = readstrfile(file)
 |   if s != 0:
 |   |   print ("   ",file,"has",len(s),"characters")
 |   else:
 |   |   print ("   There was a problem opening:",file)

(Oops, ignore the bars.)

And, forgetting file input for a minute, what about function return 
values in general; should they still be allowed to return some status or 
error codes, or does it all have to be exceptions now?


I mean, is a function allowed to still return True or False, or just 
False? (Or perhaps just nothing if the exception mechanism can signal 
either.)


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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Ned Batchelder
On Tuesday, March 22, 2016 at 10:02:41 AM UTC-4, BartC wrote:
> On 22/03/2016 13:13, Chris Angelico wrote:
> > On Tue, Mar 22, 2016 at 11:59 PM, BartC  wrote:
> 
> > The first step in any program is to write it in the very simplest way
> > possible. That usually means ignoring all error handling. And yes,
> > this is true in EVERY language - C, PHP, Pike, DeScribe Macro
> > Language, you name it. Then you try it, and you find one of two
> > things:
> 
> (Not in C; you can cause serious damage! But when I tried that approach 
> in my experimental Python programs, it wasn't popular, I recall.)
> 
> > Note, though, that "deal with" really means "deal with", and NOT
> > "print oops to the console and terminate". If all you're going to do
> > with an exception is print and terminate, *let it go*, unless it's a
> > user-triggered failure, in which case you catch it right at the very
> > highest level, and basically fall off the end of your program. The
> > number of times you have sys.exit() in an except clause should be
> > vanishingly small.
> 
> So code like the following is consigned to history?
> 
>   while 1:
>   |   file = input ("Filename (press enter to quit)? ")
>   |   if file == "": break
>   |   print ("Trying to open:",file,"...")
>   |   s = readstrfile(file)
>   |   if s != 0:
>   |   |   print ("   ",file,"has",len(s),"characters")
>   |   else:
>   |   |   print ("   There was a problem opening:",file)
> 
> (Oops, ignore the bars.)

We can certainly improve on this:

while True:
filename = input("Filename (press enter to quit)? ")
if not filename:
break
print("Trying to open: {}...".format(filename))
try:
s = readstrfile(filename)
except Exception as e:
print("   There was a problem opening {}: {}".format(filename, e))
else:
print("   {} has {} characters".format(filename, len(s)))

Some detail of the problem is now displayed.  In your code,
there's no information about what was wrong with the filename.
Was it an invalid filename for the OS? Was the file there but
the permissions prevented you from reading it? There's no way
to know.  With the exception-based code, we have the message from
the exception itself to provide the details.

> And, forgetting file input for a minute, what about function return 
> values in general; should they still be allowed to return some status or 
> error codes, or does it all have to be exceptions now?

It doesn't *have* to be exceptions.  But they are greatly preferred.
They don't clutter the semantics of your return value, and they prevent
accidents by omission.

> I mean, is a function allowed to still return True or False, or just 
> False? (Or perhaps just nothing if the exception mechanism can signal 
> either.)

Of course a function can still return True or False, if that's a reasonable
semantic.  For example, os.path.exists(filename) returns a True or False.

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


Re: Convert list to another form but providing same information

2016-03-22 Thread anantguptadbl
On Tuesday, March 22, 2016 at 12:01:10 AM UTC+5:30, Maurice wrote:
> Just figured why:
> 
> If I type this on the kernel:
> 
> weirdList = [[0]*3]*5
> 
> weirdList
> Out[257]: [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
> 
> weirdList[0][0] = 1
> 
> weirdList
> Out[259]: [[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]]
> 
> All first elements of the sublists also changes. I dunno why...

When we write [[0] * 3] * 5, the [0] * 3 list is repeated 5 times
its something like
list,list,list,list,list

if we change the 1st element of list, it gets reflected on all the 5 copies
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Chris Angelico
On Wed, Mar 23, 2016 at 1:02 AM, BartC  wrote:
>> Note, though, that "deal with" really means "deal with", and NOT
>> "print oops to the console and terminate". If all you're going to do
>> with an exception is print and terminate, *let it go*, unless it's a
>> user-triggered failure, in which case you catch it right at the very
>> highest level, and basically fall off the end of your program. The
>> number of times you have sys.exit() in an except clause should be
>> vanishingly small.
>
>
> So code like the following is consigned to history?
>
>  while 1:
>  |   file = input ("Filename (press enter to quit)? ")
>  |   if file == "": break
>  |   print ("Trying to open:",file,"...")
>  |   s = readstrfile(file)
>  |   if s != 0:
>  |   |   print ("   ",file,"has",len(s),"characters")
>  |   else:
>  |   |   print ("   There was a problem opening:",file)
>
> (Oops, ignore the bars.)

Your "else" clause there conceals the fact that it's actually
*recovering* from an error condition, by reporting it and then
returning to the main loop. So here's how I'd write it:

while "moar files":
filename = input("Filename (blank to quit): ")
if not filename: break
print("Reading %s..." % filename, end="\r")
try:
print("   %s has %d characters." % (filename, len(readfile(filename
except (IOError, OSError) as e:
print("   Cannot read %s: %s" % (filename, e))

Aside from a few trivial changes to names and text strings and such,
the one significant change is that I catch just two types of error
(I/O and OS), and *I print out the error message*. In this case, the
traceback wouldn't be very helpful, so it's dropped; but the text
message is useful *to the user*, not just the programmer. If I were
using a program like this and it didn't distinguish between "file not
found", "permission denied", "is a directory", and "disk read
failure", I would be extremely displeased.

Note that I didn't catch UnicodeDecodeError here. If the file you're
trying to read isn't a text file, the exception will terminate the
process. Perhaps you decide that this should be handled too; all you
have to do is add it to the existing except clause, or add a second
one to handle this differently (maybe just "except UnicodeDecodeError:
print('is binary')"). That's the beauty of exception handling; you
handle as many or as few types as make sense for you to handle.

> And, forgetting file input for a minute, what about function return values
> in general; should they still be allowed to return some status or error
> codes, or does it all have to be exceptions now?
>
> I mean, is a function allowed to still return True or False, or just False?
> (Or perhaps just nothing if the exception mechanism can signal either.)

Depends on what those return values mean! If they mean exceptional
conditions, perhaps they should be changed; if they mean return
values, of course they shouldn't.

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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Jon Ribbens
On 2016-03-22, Chris Angelico  wrote:
> On Wed, Mar 23, 2016 at 12:46 AM, Jon Ribbens
> wrote:
>> On 2016-03-22, Chris Angelico  wrote:
>>> The first step in any program is to write it in the very simplest way
>>> possible. That usually means ignoring all error handling. And yes,
>>> this is true in EVERY language - C, PHP, Pike, DeScribe Macro
>>> Language, you name it.
>>
>> I'm afraid I have to say I think this is absolutely terrible advice.
>> If you write code in a language that does not have exceptions (e.g. C)
>> and get it working with no error handling, the chances are
>> approximately 100% that it will stay that way and be shipped without
>> error handling, until that lack causes someone a major problem.
>
> There are languages in which it's inadvisable. But can you honestly
> say that you've never written a C program with even a single error
> check omitted, first time?

No, quite the opposite - having done it is how I know that what tends
to happen is that the error handling never gets added ;-)

> So yes, it does happen, a lot. The difference with languages like
> Python is that this actually *is* good advice in Python.

Indeed, this is why I think that exceptions are a vital part of
a high-level language (and why Java's mandatory exception-declarations
are an abomination).

> Due to a mistake in editing, the parentheses around the "true in
> EVERY language" sentence were lost, which would have made it clearer
> that this is in two distinct parts:
>
> 1) This IS what happens, whatever language you use
> 2) This is the right thing to do in Python, but not always elsewhere.
>
> My apologies for the confusion.

Ah yes with the clarification I now agree with you ;-)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Chris Angelico
On Wed, Mar 23, 2016 at 2:07 AM, Jon Ribbens
 wrote:
>> Due to a mistake in editing, the parentheses around the "true in
>> EVERY language" sentence were lost, which would have made it clearer
>> that this is in two distinct parts:
>>
>> 1) This IS what happens, whatever language you use
>> 2) This is the right thing to do in Python, but not always elsewhere.
>>
>> My apologies for the confusion.
>
> Ah yes with the clarification I now agree with you ;-)

This is why we have multiple people on the list :) I detest places
that basically have "here, send a message to this address and one
person will respond" - I wouldn't have noticed my lack of clarity, and
the recipient would have received duff advice. Thanks for ensuring the
quality of the final result :)

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


Re: need help With understanding

2016-03-22 Thread Terry Reedy

On 3/22/2016 8:49 AM, Bob Gailer wrote:

On Mar 21, 2016 5:40 PM, "Peter Pearson"  wrote:



i have currently installed Python,


What version, on what system?


and im Reading this book which
tells me i have to have IDLE, but i cant find it on my computer. do i
need to install it? and if so where do/can i find it.?



I believe IDLE is part of the Python distribution. Do a search for idle
from the python directory.


On Windows, the installer has a checkbox, default checked, to install 
tcl/tk, tkinter, and idle.  There is an IDLE icon in the Python x.y 
group in the Start menu.


I don't know the details for other systems.

--
Terry Jan Reedy

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


Re: crash while using PyCharm / Python3

2016-03-22 Thread Daniel Wilcox
Now as for *why* you needed to reinstall your graphics driver... did the
graphics driver get updated before the crash?  Or do we think something in
the java runtime for PyCharm ate libglx or friends?

I did find this PyCharm crash in which Java ate itself -- though didn't eat
any library files (as that is *very* special) -- going on out a limb here
maybe the crash was something like this, sans the markdown plugin:
https://github.com/nicoulaj/idea-markdown/issues/247


7f7b38dd9000 r-xp  08:06 926862
/usr/lib/x86_64-linux-gnu/libxcb-glx.so.0.0.0
7f7b38dd9000-7f7b38fd8000 ---p 00015000 08:06 926862
/usr/lib/x86_64-linux-gnu/libxcb-glx.so.0.0.0
7f7b38fd8000-7f7b38fda000 r--p 00014000 08:06 926862
/usr/lib/x86_64-linux-gnu/libxcb-glx.so.0.0.0
7f7b38fda000-7f7b38fdb000 rw-p 00016000 08:06 926862
/usr/lib/x86_64-linux-gnu/libxcb-glx.s

So some xcb libraries do get mapped -- but that doesn't say much really --
after all paging a library in shouldn't lead to writing to it, corrupting
it -- but copy-on-write and all that crap... so maybe.

Also from some quick reading on XCD it doesn't sound like it has anything
to do with initializing the graphics system, which is still GLX+Xlib's
job.  So whether this could even affect you at startup isn't clear to me.

https://xcb.freedesktop.org/opengl/

Late to the party but glad to hear everything worked out.  It's been
literally a decade since I worried about having working 3d graphics in
Linux, so nouveau for me.  Cheers!


On Tue, Mar 22, 2016 at 6:10 AM, Jonathan N. Little 
wrote:

> Adam wrote:
>
>> Thanks, but why fix if it ain't broke?:-)
>>
>
> No reason to.
>
>
> --
> Take care,
>
> Jonathan
> ---
> LITTLE WORKS STUDIO
> http://www.LittleWorksStudio.com
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: crash while using PyCharm / Python3

2016-03-22 Thread Big Bad Bob
On 03/21/16 17:23, Adam so wittily quipped:
> "Adam"  wrote in message 
> news:[email protected]...
>>
>> "Jonathan N. Little"  wrote in message 
>> news:[email protected]...
>>> Adam wrote:
 There ought to be a way to just reinstall the graphics subsystem rather 
 than
 an all-or-none installation approach.
>>>
>>> Yes you can. Did it for a borked install of the nVidia driver. reference 
>>> this:
>>>
>>> 
>>
>> Thanks, even after doing the following...
>>
>> Problem: Need to purge -fglrx
>>
>> Typically, the following manual commands will properly uninstall -fglrx:
>>
>>  $ sudo apt-get remove --purge xorg-driver-fglrx fglrx*
>>  $ sudo apt-get install --reinstall libgl1-mesa-glx libgl1-mesa-dri 
>> xserver-xorg-core
>>  $ sudo dpkg-reconfigure xserver-xorg
>>
>> I still get that dreaded "The system is running in low-graphics mode" 
>> error.
>> And, recovery mode failsafeX and Ctrl+Alt+F1 hangs with the following...
>>
>>
>> Initializing built-in extension MIT-SCREEN-SAVER
>> Initializing built-in extension DOUBLE-BUFFER
>> Initializing built-in extension RECORD
>> Initializing built-in extension DPMS
>> Initializing built-in extension Present
>> Initializing built-in extension DRI3
>> Initializing built-in extension X-Resource
>> Initializing built-in extension XVideo
>> Initializing built-in extension XVideo-MotionCompensation
>> Initializing built-in extension SELinux
>> Initializing built-in extension XFree86-VidModeExtension
>> Initializing built-in extension XFree86-DGA
>> Initializing built-in extension XFree86-DRI
>> Initializing built-in extension DRI2
>> Loading extension GLX
>> 
>>
> 
> After trying the following...
> 
> http://askubuntu.com/questions/577093/how-to-install-gnome-desktop
> 
> $ sudo apt-get update
> $ sudo apt-get install gnome-shell
> 
> 
> http://tipsonubuntu.com/2014/06/06/change-display-manager-ubuntu-14-04/
> 
> $ sudo dpkg-reconfigure lightdm
> 
> I am now able to login.  But,
> not sure what happened to the "lightdm" display manager.
> I am now using "gdm" display manager.

if you're able to boot up by changing things *like* the display manager,
you might want to take a look at the X11 configuration directly.  Adding
"more cruft" to your system (i.e. gdm) isn't necessarily going to 'fix'
a problem that's related to the X11 configuration.

[it's one reason why I generally prefer to boot to command line rather
than into a GUI for a typical linux install]

as an example, you could save your xorg.conf file
  /etc/X11/xorg.conf

and generate a new one, using 'xorg -configure' (as root).

I'm guessing that when you installed the 'PyCharm' package, "some other
dependent package" did something undesirable to your xorg.conf file.

That would MOST CERTAINLY cause a hang during the desktop startup.

it might also be fixable by re-configuring your installed packages,
rather than a full-blown re-install from scratch.

dpkg-reconfigure -a

[the man page warns "it may take a long time" - yeah, probably will]


Keep in mind that adding gdm afterwards *might* have done the
'reconfigure' on the problem package(s) already.  So adding 'gdm'
instead of whatever login manager you were using before [along with all
of its dependent packages] would most likely have forced "the problem
package" to re-configure.  That very well might have "fixed" the problem
on its own.  So my suggestion here would be to remove this 'new' package
and see if the problem comes back.  Most likely it won't.


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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Michael Torrie
On 03/22/2016 06:59 AM, BartC wrote:
> I'm not sure I follow. Your solution to dealing with the scenarios 
> raised by Steven D'Aprano is to:
> 
> (1) Not bother with exceptions at all inside the function

Correct, if your function is not equipped to handle this exceptional
circumstance and do the right thing, the right thing to do is let the
caller deal with it.  Otherwise debugging is very hard if not
impossible.  In your former example, a 0 return code means what exactly?
File not found? File exists but permission is denied?
> 
> (2) Not bother with them in the user code either

Again, it depends on whether the user code is equipped to react to the
exception and do the right thing.  I probably would catch file and i/o
errors like file-not-found and print a specific message out (or a dialog
box).  Or loop back to try again if the user was picking a file to work
with.

And despite the impression you may have gotten, it is appropriate to
look before you leap. Using os.exists() and other pre-flight checks are
appropriate.

> (3) Let any errors just crash out (raise a Python system error) (just 
> like I did in my original jpeg program which I was called out on)

Any exceptions your program is not explicitly equipped to deal with
should indeed bubble up to the OS and crash out.  After all it's by
definition an exceptional event and the state of your program and data
after this point is not reliable if such an event is ignored.  And it
provides valuable information an end user can pass back to you as a
developer to find bugs you missed.

> (4) Or if the user code does want to check for certain errors (like, 
> File Not Found, by far the most likely, and so that it can deal with 
> that and continue executing), it now has to go and dig out docs for ... 
> what? The user code needs to know what is going on inside the supposedly 
> opaque function it's calling.

Good documentation should describe exactly what exceptions a function or
library raises and why.  I tend to try to follow the example of Python's
standard library. I keep my exception classes few, and raise a good
error message with it.

But often times the exceptions we're talking about are standard Python
exceptions arising from things like I/O, not custom library classes.

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


!! Immediate Interview: BizTalk/Consultanta at (Princeton, NJ)

2016-03-22 Thread sourav524 . itscient
Hi , 
Please go through the below job description and let me know your interest.
Please revert me:  [email protected].

Position: BizTalk/ Consultant

Location: Princeton, NJ

Duration: 6+ Months

Skills:

* Mandatory Skill (List out all Technical Skills required along with domain 
skill required)
o Experience in technologies like MS BIZTALK 2010/13(At least 6+ yrs.), 
Microsoft SharePoint, .NET, and Visual Studio
* Non Mandatory Skill
* Knowledgeable with integrating SAP business partner.
* Strong knowledge and deep understanding on ACORD RLC messages, AMS Gateway 
implementation, EBOT, ECOT
* Experience with Xerox EIP for MFD, experience with configuring XEROX MFD and 
customize the MFD display.
* Experience with Exchange server and outlook add-in
* Non-Technical Requirements

Required Experience (Same as Relevant Experience):

* Strong programming skills with BizTalk server. Proficient with BizTalk 
orchestration, mapper, adapters. Proficiency in creating pipeline components
* Able to apply BizTalk design patterns
* Strong understanding of Object oriented programming. Able to apply Design 
patterns
* Ability to work with limited supervision
* Able to provide good quality design spec and documentation
* Analytical and communication skills. Quickly understand business requirements 
and provide optimal solution
* Programming skills in WCF, web services, XSLT, XML, XSD
* SQL programming skills. Able to optimize and tune queries. Proficient in 
creating complex stored procedures and views.
* ASP.net, C#, CSS, ADO.net
* Installations, Deployment and troubleshooting
* Strong experience with SharePoint services and creating web parts
* Experience with CAML query.
* BAM, BAM API, BAM Portal knowledge and experience
* Strong understanding of BizTalk server / performance tuning
* SOA  architecture design and extensive ESB Toolkit knowledge and experience.

Job Responsibilities:

* Responsible for Solution, Estimation;
* Solution Proposition to Clients;
* Build client relationships in existing accounts;
* Review Statement of Work;
* Drive Solution / Framework Creation initiatives for customer;
* Provide Architecture Guidelines, Integration roadmap and Governance to all 
Integration projects in the organization.

Thanks & Regards 
   
Sourav Paul | Technical Recruiter
IT-SCIENT LLC, Fremont, CA, USA  
Email: [email protected]
Phone: 510-972-5265 | Fax: 877-701-5240
|web: www.itscient.com
-- 
https://mail.python.org/mailman/listinfo/python-list


how to cache invalidation

2016-03-22 Thread Sven R. Kunze

Hi everybody,

I got another module up and running: xcache
Background described here: 
http://srkunze.blogspot.com/2016/03/safe-cache-invalidation.html


We needed a way to safely invalidate rlu_caches once a Web request has 
been finished. So, we came up with a solution using garbage collection 
and extended this to context managers for other purposes. Maybe, it can 
be useful to other Python devs as well. :-)


Let me know if you need help with it.

Best,
Sven
--
https://mail.python.org/mailman/listinfo/python-list


Re: crash while using PyCharm / Python3

2016-03-22 Thread Adam

"Big Bad Bob"  wrote in message 
news:[email protected]...
> On 03/21/16 17:23, Adam so wittily quipped:
>> "Adam"  wrote in message
>> news:[email protected]...
>>>
>>> "Jonathan N. Little"  wrote in message
>>> news:[email protected]...
 Adam wrote:
> There ought to be a way to just reinstall the graphics subsystem 
> rather
> than
> an all-or-none installation approach.

 Yes you can. Did it for a borked install of the nVidia driver. 
 reference
 this:

 
>>>
>>> Thanks, even after doing the following...
>>>
>>> Problem: Need to purge -fglrx
>>>
>>> Typically, the following manual commands will properly uninstall -fglrx:
>>>
>>>  $ sudo apt-get remove --purge xorg-driver-fglrx fglrx*
>>>  $ sudo apt-get install --reinstall libgl1-mesa-glx libgl1-mesa-dri
>>> xserver-xorg-core
>>>  $ sudo dpkg-reconfigure xserver-xorg
>>>
>>> I still get that dreaded "The system is running in low-graphics mode"
>>> error.
>>> And, recovery mode failsafeX and Ctrl+Alt+F1 hangs with the following...
>>>
>>>
>>> Initializing built-in extension MIT-SCREEN-SAVER
>>> Initializing built-in extension DOUBLE-BUFFER
>>> Initializing built-in extension RECORD
>>> Initializing built-in extension DPMS
>>> Initializing built-in extension Present
>>> Initializing built-in extension DRI3
>>> Initializing built-in extension X-Resource
>>> Initializing built-in extension XVideo
>>> Initializing built-in extension XVideo-MotionCompensation
>>> Initializing built-in extension SELinux
>>> Initializing built-in extension XFree86-VidModeExtension
>>> Initializing built-in extension XFree86-DGA
>>> Initializing built-in extension XFree86-DRI
>>> Initializing built-in extension DRI2
>>> Loading extension GLX
>>> 
>>>
>>
>> After trying the following...
>>
>> http://askubuntu.com/questions/577093/how-to-install-gnome-desktop
>>
>> $ sudo apt-get update
>> $ sudo apt-get install gnome-shell
>>
>>
>> http://tipsonubuntu.com/2014/06/06/change-display-manager-ubuntu-14-04/
>>
>> $ sudo dpkg-reconfigure lightdm
>>
>> I am now able to login.  But,
>> not sure what happened to the "lightdm" display manager.
>> I am now using "gdm" display manager.
>
> if you're able to boot up by changing things *like* the display manager,
> you might want to take a look at the X11 configuration directly.  Adding
> "more cruft" to your system (i.e. gdm) isn't necessarily going to 'fix'
> a problem that's related to the X11 configuration.
>
> [it's one reason why I generally prefer to boot to command line rather
> than into a GUI for a typical linux install]
>
> as an example, you could save your xorg.conf file
>  /etc/X11/xorg.conf

No such file on my system.  Is it even needed ?


>
> and generate a new one, using 'xorg -configure' (as root).
>
> I'm guessing that when you installed the 'PyCharm' package, "some other
> dependent package" did something undesirable to your xorg.conf file.

I no longer think PyCharm / Python3 is the cause of the crash.
It was just a coincidence.

Search for "lightdm problem ubuntu 14.04"


>
> That would MOST CERTAINLY cause a hang during the desktop startup.

lightdm was failing.


>
> it might also be fixable by re-configuring your installed packages,
> rather than a full-blown re-install from scratch.
>
> dpkg-reconfigure -a
>
> [the man page warns "it may take a long time" - yeah, probably will]
>
>
> Keep in mind that adding gdm afterwards *might* have done the
> 'reconfigure' on the problem package(s) already.  So adding 'gdm'
> instead of whatever login manager you were using before [along with all
> of its dependent packages] would most likely have forced "the problem
> package" to re-configure.  That very well might have "fixed" the problem
> on its own.  So my suggestion here would be to remove this 'new' package
> and see if the problem comes back.  Most likely it won't.
>

Thanks, but it's working fine now.:-)


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


Re: crash while using PyCharm / Python3

2016-03-22 Thread Adam

"Jonathan N. Little"  wrote in message 
news:[email protected]...
> Adam wrote:
>> Thanks, but why fix if it ain't broke?:-)
>
> No reason to.

Yup, I agree.


>
> -- 
> Take care,
>
> Jonathan
> ---
> LITTLE WORKS STUDIO
> http://www.LittleWorksStudio.com 


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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Chris Angelico
On Wed, Mar 23, 2016 at 6:43 AM, Michael Torrie  wrote:
> And despite the impression you may have gotten, it is appropriate to
> look before you leap. Using os.exists() and other pre-flight checks are
> appropriate.

Hmm, can you justify this? Remember, as soon as any other process has
done anything, your LBYL is invalid. You check that the file exists,
then it gets deleted. Or you check that it doesn't, and bam, suddenly
it does. The only way to be certain is to do an operation that
enforces it on the hard disk itself - either open the file (after
that, deletion can't affect you - on some OSes, deletion can't
happen), or create it and hold it open exclusively (nobody else can
create a file with that name).

>> (4) Or if the user code does want to check for certain errors (like,
>> File Not Found, by far the most likely, and so that it can deal with
>> that and continue executing), it now has to go and dig out docs for ...
>> what? The user code needs to know what is going on inside the supposedly
>> opaque function it's calling.
>
> Good documentation should describe exactly what exceptions a function or
> library raises and why.  I tend to try to follow the example of Python's
> standard library. I keep my exception classes few, and raise a good
> error message with it.
>
> But often times the exceptions we're talking about are standard Python
> exceptions arising from things like I/O, not custom library classes.

If you have documentation like this, it should list only the
exceptions that you explicitly raise, not those that can bubble up
through it - this is where Java gets it wrong, IMO. If you attempt to
read from a file that gets passed in as an argument, AttributeError
could get raised, but you shouldn't document that; but if you have a
line of code that says "raise InconsistentDNSRecordError", then yes,
that's something worth documenting.

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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Steven D'Aprano
On Wed, 23 Mar 2016 01:02 am, BartC wrote:

> And, forgetting file input for a minute, what about function return
> values in general; should they still be allowed to return some status or
> error codes, or does it all have to be exceptions now?

It doesn't *have to* be exceptions, but exceptions are considered to be a
generally better approach. Some people disagree, must famously Rob Pike,
the highly respected creator of Go (the language, not the ancient Chinese
board game). But Go's approach of returning error codes is most certainly
not Pythonic. (It might be Go-thonic :-)


> I mean, is a function allowed to still return True or False, or just
> False? (Or perhaps just nothing if the exception mechanism can signal
> either.)


You can answer this question yourself by looking at what functions are
provided in the standard library and built-ins:

py> "hello world".find("goodbye")
-1
py> "hello world".startswith("goodbye")
False



-- 
Steven

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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Chris Angelico
On Wed, Mar 23, 2016 at 12:14 PM, Steven D'Aprano  wrote:
>> I mean, is a function allowed to still return True or False, or just
>> False? (Or perhaps just nothing if the exception mechanism can signal
>> either.)
>
>
> You can answer this question yourself by looking at what functions are
> provided in the standard library and built-ins:
>
> py> "hello world".find("goodbye")
> -1
> py> "hello world".startswith("goodbye")
> False

To add to the "experiment" advice, a general rule of thumb: Any
function/method that appears to be asking a yes/no question should be
happy to return True/False for the two answers. It can still raise if
the question doesn't make sense:

>>> "hello world".startswith(3.14159)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: startswith first arg must be str or a tuple of str, not float
>>> "hello world".startswith(b"\x41")
Traceback (most recent call last):
  File "", line 1, in 
TypeError: startswith first arg must be str or a tuple of str, not bytes

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


Key Binding Problem

2016-03-22 Thread Wildman via Python-list
Platform: Linux
Python: v.2.7.9
Tkinter: v.8.6.2

My program has some buttons for file operations, load_image,
save_image, and quit.  I would like to bind a key that will
execute the procedures for each of the buttons.  The binding
for the quit button was easy...

root.bind("", quit)
root.bind("", quit)

That works but it not executing a quit button procedure.
It is merely executing an internal command.  My problem is
calling an actual button procedure.  Over the last several
hours I have tried many different syntax arrangements and
I keep getting "object not defined" errors.  I also tried
placing the bind statements into other places in the code.
I have run out of ideas.

Below is a basic skeleton of my code.  Any help appreciated.

#!/usr/bin/env python

try:
import Tkinter as tk
from Tkinter import Tk
except ImportError:
import tkinter as tk
from tkinter import Tk
import tkFileDialog, tkMessageBox
import Image, ImageTk
import base64, io, os, subprocess

class cv():

# global variables

class Window(tk.Frame):

def __init__(self, master = None):
tk.Frame.__init__(self,master)
self.master = master
self.init_window()

def init_window(self):
self.master.title("My Program")
self.pack(fill=tk.BOTH, expand=1)
self.quitButton = tk.Button(self,
text="Quit",
underline=0,
width=10,
command=self.quit)
self.quitButton.place(x=224, y=422)

self.loadButton = tk.Button(self,
text="Load Image",
underline=0,
width = 10,
command=self.load_image)
self.loadButton.place(x=138, y=46)

# create the rest of the widgets

def load_image(self):
# load image file

def save_image(self):
# save the image

def other procedure definitions

root = Tk()
root.bind("", quit)  # these two work
root.bind("", quit)
root.bind("", load_image)  # these do not work
root.bind("", load_image)  # object not defined errors
root.bind("", save_image)
root.bind("", save_image)
root.minsize(width=554, height=462)
root.maxsize(width=554, height=462)
app = Window(root)
root.mainloop()

My question is how do I coax bind into executing the
button procedures?  Or is there a way to generate the
button click event from the binding?

-- 
 GNU/Linux user #557453
"Be at war with your vices, at peace with your neighbors,
and let every new year find you a better man."
  -Benjamin Franklin
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Key Binding Problem

2016-03-22 Thread MRAB

On 2016-03-23 02:46, Wildman via Python-list wrote:

Platform: Linux
Python: v.2.7.9
Tkinter: v.8.6.2

My program has some buttons for file operations, load_image,
save_image, and quit.  I would like to bind a key that will
execute the procedures for each of the buttons.  The binding
for the quit button was easy...

root.bind("", quit)
root.bind("", quit)

That works but it not executing a quit button procedure.
It is merely executing an internal command.  My problem is
calling an actual button procedure.  Over the last several
hours I have tried many different syntax arrangements and
I keep getting "object not defined" errors.  I also tried
placing the bind statements into other places in the code.
I have run out of ideas.

Below is a basic skeleton of my code.  Any help appreciated.

#!/usr/bin/env python

try:
 import Tkinter as tk
 from Tkinter import Tk
except ImportError:
 import tkinter as tk
 from tkinter import Tk
import tkFileDialog, tkMessageBox
import Image, ImageTk
import base64, io, os, subprocess

class cv():

 # global variables

class Window(tk.Frame):

 def __init__(self, master = None):
 tk.Frame.__init__(self,master)
 self.master = master
 self.init_window()

 def init_window(self):
 self.master.title("My Program")
 self.pack(fill=tk.BOTH, expand=1)
 self.quitButton = tk.Button(self,
 text="Quit",
 underline=0,
 width=10,
 command=self.quit)
 self.quitButton.place(x=224, y=422)

 self.loadButton = tk.Button(self,
 text="Load Image",
 underline=0,
 width = 10,
 command=self.load_image)
 self.loadButton.place(x=138, y=46)

 # create the rest of the widgets

 def load_image(self):
 # load image file

 def save_image(self):
 # save the image

 def other procedure definitions

root = Tk()
root.bind("", quit)  # these two work
root.bind("", quit)
root.bind("", load_image)  # these do not work
root.bind("", load_image)  # object not defined errors
root.bind("", save_image)
root.bind("", save_image)
root.minsize(width=554, height=462)
root.maxsize(width=554, height=462)
app = Window(root)
root.mainloop()

My question is how do I coax bind into executing the
button procedures?  Or is there a way to generate the
button click event from the binding?

It won't let you bind to a function called "load_image" because there 
isn't a function called "load_image"!


The "Window" class, however, does have a method with that name.

Try binding the keys in Window.__init__ or Window.init_window:

def init_window(self):
...
root.bind("", self.load_image)

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


Re: Key Binding Problem

2016-03-22 Thread Terry Reedy

On 3/22/2016 10:46 PM, Wildman via Python-list wrote:

Platform: Linux
Python: v.2.7.9
Tkinter: v.8.6.2

My program has some buttons for file operations, load_image,
save_image, and quit.  I would like to bind a key that will
execute the procedures for each of the buttons.  The binding
for the quit button was easy...

root.bind("", quit)
root.bind("", quit)

That works but it not executing a quit button procedure.
It is merely executing an internal command.  My problem is
calling an actual button procedure.  Over the last several
hours I have tried many different syntax arrangements and
I keep getting "object not defined" errors.  I also tried
placing the bind statements into other places in the code.
I have run out of ideas.

Below is a basic skeleton of my code.  Any help appreciated.

#!/usr/bin/env python

try:
 import Tkinter as tk
 from Tkinter import Tk


The second import is not needed.  tk.Tk is short and should be called 
just once.



except ImportError:
 import tkinter as tk
 from tkinter import Tk


ditto.


import tkFileDialog, tkMessageBox


These are 2.x only and should be after the Tkinter import.
For 3.x, import tk.filedialog, tk.messagebox

--
Terry Jan Reedy

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


Re: GAPI -- Sharing a post to Social Networking Pages from my App

2016-03-22 Thread Karthik Reddy
On Tuesday, March 22, 2016 at 4:48:37 PM UTC+5:30, Steven D'Aprano wrote:
> On Tue, 22 Mar 2016 09:37 pm, Karthik Reddy wrote:
> 
> > The error I am getting is "Uncaught ReferenceError: gapi is not defined"
> 
> 
> Have you tried googling for it? That's a Javascript error:
> 
> https://duckduckgo.com/html/?q=uncaught+reference+error+gapi+is+not+defined
> 
> 
> 
> -- 
> Steven

Hi I resolved the error but I am not able to post my post .
I tried 
https://developers.google.com/+/domains/authentication/#authorizing_requests_with_oauth_20

I am getting the below error When i copied the url.

Error: invalid_client

The OAuth client was not found.

Even i gave Client_id correctly

Thanks,
Karthik 

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


Re: Key Binding Problem

2016-03-22 Thread Wildman via Python-list
On Wed, 23 Mar 2016 03:02:51 +, MRAB wrote:

> On 2016-03-23 02:46, Wildman via Python-list wrote:
>> My question is how do I coax bind into executing the
>> button procedures?  Or is there a way to generate the
>> button click event from the binding?
>>
> It won't let you bind to a function called "load_image" because there 
> isn't a function called "load_image"!
> 
> The "Window" class, however, does have a method with that name.
> 
> Try binding the keys in Window.__init__ or Window.init_window:
> 
>  def init_window(self):
>  ...
>  root.bind("", self.load_image)

Here is what I tried:

class Window(tk.Frame):

def __init__(self, master = None):
tk.Frame.__init__(self,master)
self.master = master
root.bind("l", self.load_image)

I get this error and it doesn't make any sense to me:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1535, in __call__
return self.func(*args)
TypeError: load_image() takes exactly 1 argument (2 given)

-- 
 GNU/Linux user #557453
The cow died so I don't need your bull!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Key Binding Problem

2016-03-22 Thread Wildman via Python-list
On Tue, 22 Mar 2016 23:52:57 -0400, Terry Reedy wrote:

> On 3/22/2016 10:46 PM, Wildman via Python-list wrote:
>> Platform: Linux
>> Python: v.2.7.9
>> Tkinter: v.8.6.2
>>
>> My program has some buttons for file operations, load_image,
>> save_image, and quit.  I would like to bind a key that will
>> execute the procedures for each of the buttons.  The binding
>> for the quit button was easy...
>>
>> root.bind("", quit)
>> root.bind("", quit)
>>
>> That works but it not executing a quit button procedure.
>> It is merely executing an internal command.  My problem is
>> calling an actual button procedure.  Over the last several
>> hours I have tried many different syntax arrangements and
>> I keep getting "object not defined" errors.  I also tried
>> placing the bind statements into other places in the code.
>> I have run out of ideas.
>>
>> Below is a basic skeleton of my code.  Any help appreciated.
>>
>> #!/usr/bin/env python
>>
>> try:
>>  import Tkinter as tk
>>  from Tkinter import Tk
> 
> The second import is not needed.  tk.Tk is short and should be called 
> just once.
> 
>> except ImportError:
>>  import tkinter as tk
>>  from tkinter import Tk
> 
> ditto.
> 
>> import tkFileDialog, tkMessageBox
> 
> These are 2.x only and should be after the Tkinter import.
> For 3.x, import tk.filedialog, tk.messagebox

Thanks for the info.  Making the changes...

-- 
 GNU/Linux user #557453
The cow died so I don't need your bull!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Larry Hudson via Python-list

I didn't see anyone responding to this, so I'll pop in here...

On 03/22/2016 04:05 AM, BartC wrote:
[...]

(Suppose you need both the value and its index in the loop? Then the one-line 
for above won't
work. For example, 'something' is [10,20,30] and you want to print:

  0: 10
  1: 20
  2: 30 )



Your lack of knowledge of Python is showing again...
Python has "enumerate" just for this purpose.  Your example would be written as:

for i, val in enumerate(something):
print('{}: {}'.format(i, val))

However, in this specific example, the i is not used as an actual index but rather a 
line-number.  So you can change "enumerate(something)" to "enumerate(something, 1)" to set the 
starting number to 1 instead of the default 0, and the lines will be numbered 1, 2 and 3 rather 
than 0, 1 and 2.


As always, the choice is yours.  ;-)


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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Ben Finney
Steven D'Aprano  writes:

> On Mon, 21 Mar 2016 06:47 pm, Ben Finney wrote:
>
> > Bart can show good faith by *learning* idiomatic Python, with the
> > humility of a beginner. And also by refraining from rhetoric about
> > how bad Python's performance is, until he gains experience to make
> > those claims.
>
> "Humility of a beginner"... what a strange phrase to use about
> somebody who has been programming for decades.

What a strange reading of what I wrote. Clearly I'm referring to the
fact Bart is a beginner in Python.

To show good faith in learning Python – if indeed that is what Bart
wants, which I'm not convinced of given how much he prefers to talk
about a different private programming language instead – then he should
be taking advantage of the teaching resources that have been offered
numerous times.

> What exactly is the problem here? Is it that Bart hasn't earned the
> right to say what we all know, that Python is slow, because he's an
> outsider?

The problem is that Bart simultaneously is a beginner at Python, and
expresses astonishment that everyone shrugs when Bart's
dreadfully-written code performs so badly.

Good faith is contradicted by asserting knowledge of Python, complaining
about how some deliberately non-idiomatic Python code is performing
poorly, dismissing suggestions for improvement — specifically in the
context of someone who admittedly knows so little about Python.

-- 
 \   “… one of the main causes of the fall of the Roman Empire was |
  `\that, lacking zero, they had no way to indicate successful |
_o__)  termination of their C programs.” —Robert Firth |
Ben Finney

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


Re: GAPI -- Sharing a post to Social Networking Pages from my App

2016-03-22 Thread Karthik Reddy
On Wednesday, March 23, 2016 at 9:43:21 AM UTC+5:30, Karthik Reddy wrote:
> On Tuesday, March 22, 2016 at 4:48:37 PM UTC+5:30, Steven D'Aprano wrote:
> > On Tue, 22 Mar 2016 09:37 pm, Karthik Reddy wrote:
> > 
> > > The error I am getting is "Uncaught ReferenceError: gapi is not defined"
> > 
> > 
> > Have you tried googling for it? That's a Javascript error:
> > 
> > https://duckduckgo.com/html/?q=uncaught+reference+error+gapi+is+not+defined
> > 
> > 
> > 
> > -- 
> > Steven
> 
> Hi I resolved the error but I am not able to post my post .
> I tried 
> https://developers.google.com/+/domains/authentication/#authorizing_requests_with_oauth_20
> 
> I am getting the below error When i copied the url.
> 
> Error: invalid_client
> 
> The OAuth client was not found.
> 
> Even i gave Client_id correctly
> 
> Thanks,
> Karthik
Hi Steven I resolved this error also Now I am getting a pop up for google 
sharing but If click on share button its not sharing.Any help please
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Steven D'Aprano
On Wednesday 23 March 2016 09:23, Chris Angelico wrote:

> On Wed, Mar 23, 2016 at 6:43 AM, Michael Torrie  wrote:
>> And despite the impression you may have gotten, it is appropriate to
>> look before you leap. Using os.exists() and other pre-flight checks are
>> appropriate.
> 
> Hmm, can you justify this? Remember, as soon as any other process has
> done anything, your LBYL is invalid. 

"Time of check to time of use":

https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use

Fortunately, not all such "bugs" are of equal severity. In this case, there 
are two failure modes. Consider a *false positive* bug: we think the file 
exists when it actually doesn't.

if os.path.exists(filename):
os.unlink(filename)  # some other process does this
open(filename)


This is probably bad. At best, we get some sort of unhandled exception. At 
worst, we get some sort of TOCTTOU security vulnerability.

Consider a *false negative* bug: we think the file doesn't exist, when it 
actually does, and report an error:

if os.path.exists(filename):
...
else:
open(filename, 'w').write('stuff')  # some other process does this
print("No such file, please try again.")


This is probably trivial. The user simply tries again, or refreshes the 
application's "file open" selector, or something similar. No harm done.


Or consider scripting a file rename:


for old, new in zip(oldnames, newnames):
if os.path.exists(new):
print("skipping...")
os.rename(old, new)


Is it safe? Strictly speaking, no, but for a single user computer, it's 
probably safe enough. If I'm busy saving new files to a directory at the 
same time as I'm running a bulk rename of the files in that same directory, 
I probably deserve to have data loss :-)

(But having said that, if someone can give a recipe for the right way to do 
a file rename without overwriting existing files, I'd love to see it.)



-- 
Steve

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


Re: The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

2016-03-22 Thread Chris Angelico
On Wed, Mar 23, 2016 at 5:07 PM, Steven D'Aprano
 wrote:
> Fortunately, not all such "bugs" are of equal severity. In this case, there
> are two failure modes. Consider a *false positive* bug: we think the file
> exists when it actually doesn't.
>
> if os.path.exists(filename):
> os.unlink(filename)  # some other process does this
> open(filename)
>
>
> This is probably bad. At best, we get some sort of unhandled exception.

Yes - and it's exactly why it's not worth bothering with the 'exists'
check. Your code would end up looking like this:

if os.path.exists(filename):
try:
open(filename)
except FileNotFoundError:
# file got deleted out from under you
else:
# file doesn't exist

Which is exactly why error handling (whether with structured
exceptions or error codes) is better than LBYL for anything involving
the file system, or shared resources and concurrency, or anything with
a potential TOCTTOU discrepancy.

All the other situations (apart from renaming) are handled the same
way - sure, the consequences aren't as serious, but it's just as easy
to use the same technique everywhere. I don't know of a cross-platform
way to rename without overwriting, but the "mv" command on my system
has a --no-clobber option, and the underlying rename system call seems
to have a non-standard flags parameter that can be set to
RENAME_NOREPLACE to prevent overwriting. This is generally the way to
fix it; it's only in the system call that this can actually be done
reliably (hence things like temp file creation are done with flags to
the file-open syscall).

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


Re: Key Binding Problem

2016-03-22 Thread Terry Reedy

On 3/23/2016 12:28 AM, Wildman via Python-list wrote:

On Wed, 23 Mar 2016 03:02:51 +, MRAB wrote:


On 2016-03-23 02:46, Wildman via Python-list wrote:

My question is how do I coax bind into executing the
button procedures?  Or is there a way to generate the
button click event from the binding?


It won't let you bind to a function called "load_image" because there
isn't a function called "load_image"!

The "Window" class, however, does have a method with that name.

Try binding the keys in Window.__init__ or Window.init_window:

  def init_window(self):
  ...
  root.bind("", self.load_image)


Here is what I tried:

class Window(tk.Frame):

 def __init__(self, master = None):
 tk.Frame.__init__(self,master)
 self.master = master
 root.bind("l", self.load_image)

I get this error and it doesn't make any sense to me:

Exception in Tkinter callback
Traceback (most recent call last):
   File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1535, in __call__
 return self.func(*args)
TypeError: load_image() takes exactly 1 argument (2 given)


Event handlers must have one parameter (other than 'self' for methods), 
the event, as that is what they will be passed.  You defined load_image 
like this.


def load_image(self):
# load image file

It should be this

def load_image(self, event):
# load image file

You are free to ignore the event object and some people then name the 
parameter '_' (or dummy) to signify that it will be ignored.


def load_image(self, _):
# load image file

You must pass the bound method, as you did, and not the function itself 
(which has two parameters).


--
Terry Jan Reedy

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