Re: codecs.StreamRecoder not doing what I expected.

2015-12-13 Thread Peter Otten
D'Arcy J.M. Cain wrote:

> On Sat, 12 Dec 2015 21:35:36 +0100
> Peter Otten <[email protected]> wrote:
>> def read_file(filename):
>> for encoding in ["utf-8", "iso-8859-1"]:
>> try:
>> with open(filename, encoding=encoding) as f:
>> return f.read()
>> except UnicodeDecodeError:
>> pass
>> raise AssertionError("unreachable")
> 
> I replaced this in my test and it works.  However, I still have a
> problem with my actual code.  The point of this code was that I expect
> all the files that I am reading to be either ASCII, UTF-8 or LATIN-1
> and I want to normalize my input.  My problem may actually be elsewhere.
> 
> My application is a web page of my wife's recipes.  She has hundreds of
> files with a recipe in each one.  Often she simply typed them in but
> sometimes she cuts and pastes from another source and gets non-ASCII
> characters.  So far they seem to fit in the three categories above.
> 
> I added test prints to sys.stderr so that I can see what is happening.
> In one particular case I have this "73 61 75 74 c3 a9" in the file.
> When I open the file with
> "open(filename, "r", encoding="utf-8").read()" I get what appears to be
> a latin-1 string.  

No, you get unicode. The escape code for the 
'LATIN SMALL LETTER E WITH ACUTE' codepoint just happens to be the same as 
its latin-1 value:

>>> print(ascii("é"))
'\xe9'
>>> print("é".encode("latin1"))
b'\xe9'

> I print it to stderr and view it in the web log.
> The above string prints as "saut\xe9".  The last is four actual
> characters in the file.
> 
> When I try to print it to the web page it fails because the \xe9
> character is not valid ASCII.  

Can you give some code that reproduces the error? What is the traceback?

> However, my default encoding is utf-8.

That doesn't matter. sys.stout.encoding/sys.stderr.encoding are relevant.

> Other web pages on the same server display fine.
> 
> I have the following in the Apache config by the way.
> 
> SetEnv PYTHONIOENCODING utf8
> 
> So, my file is utf-8, I am reading it as utf-8, my Apache server output
> is set to utf-8.  How is ASCII sneaking in?
 
I don't know. Have you verified that python "sees" the setting, e. g. with

import os
import sys
ioencoding = os.environ.get("PYTHONIOENCODING")
assert ioencoding == "utf8"
assert sys.stdout.encoding == ioencoding
assert sys.stderr.endoding == ioencoding

Have you tried setting LANG as Oscar suggested in the other thread?

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


Re: XMPP pub sub setup and working

2015-12-13 Thread dieter
[email protected] writes:

> I am using xmpppy python library to connect with XMPP server(ejabberd2) but 
> unable to connect and actually don't have clarity on how to connect, 
> authenticate and send a message to the server.  
> If possible please provide some code snippet using XMPPPY.
>
> This is what I have tried:
>
> In [1]: from xmpp import Client
>
> In [2]: cl = Client(server='176.9.18.111', 5280)
>
>   File "", line 1
>
> cl = Client(server='176.9.18.111', 5280)
>
> SyntaxError: non-keyword arg after keyword arg

A wrong call of the "Client" class:

  If you pass a parameter value in the form "="
  (which you do for "server"), this is called a "keyword arg[ument]".
  If you pass it in the form "", this is called
  a "positional" or "non keyword arg[ument]".

  The error message tells you that you must not pass
  a positional argument after a keyword argument (what you
  do above).

Likely, you can use "Client('176.9.18.111', 5280)" or
"Client(server='176.9.18.111', port=5280)".
Both should get rid of the "SyntaxError" - but, of course,
you still have the issue with authentication.

Have a look at the so called "signature" of "Client".
The "signature" of a callable (usually function, method or class)
tells you what parameters are available and what names
(and potentially default values) they have.
You might find in the signature for "Client" parameters which
hint towards authentication (e.g. "user" and "password").
If so, pass values identifying yourself.


I heavily use Python's builtin "help" function:
"help(obj)" provides documentation for object "obj".
Thus, "help(Client)" will display information about "Client".
If it is indeed a class (which I assume), then the documentation
will (among others) list the methods. The signature for "Client"
is in this case, the signature of its "__init__" method (without
the initial "self").


> In [3]: cl = Client(server='176.9.18.111', port =5280)
> Invalid debugflag given: always
> Invalid debugflag given: nodebuilder
> DEBUG: 
> DEBUG: Debug created for 
> /Users/gathole/.virtualenvs/driveu/lib/python2.7/site-packages/xmpp/client.py
> DEBUG:  flags defined: always,nodebuilder

The output above is a bit strange - are you sure, you did not
have requested debugging in some way (not shown above)?

> In [4]: cl.connect()
> ...
> DEBUG: socket   sent  
>xmlns:stream="http://etherx.jabber.org/streams"; >
> DEBUG: socket   error Socket error while receiving data
> DEBUG: client   stop  Disconnect detected

Apparently, the server was not satisfied with the connection
proceedure and has closed the communication stream.

Check available documentation for the server you try to connect
about the connection requirements.
If there is no such documentation, you might try to contact
the server administrator to find out the relevant details.

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


Re: codecs.StreamRecoder not doing what I expected.

2015-12-13 Thread Laura Creighton
In a message of Sun, 13 Dec 2015 01:35:45 -0500, "D'Arcy J.M. Cain" writes:
>When I try to print it to the web page it fails because the \xe9
>character is not valid ASCII.  However, my default encoding is utf-8.
>Other web pages on the same server display fine.
>
>I have the following in the Apache config by the way.
>
>SetEnv PYTHONIOENCODING utf8
>
>So, my file is utf-8, I am reading it as utf-8, my Apache server output
>is set to utf-8.  How is ASCII sneaking in?

What is your sys.stdout.encoding ?

just import sys and print the thing.

I think you will find that it is not what you expect.

Laura

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


Python IO Redirection to Console

2015-12-13 Thread austin aigbe
Hello,

I am trying to redirect the IO (stdout, stdin and stderr) to the console.
Is there a Python module for this?

Thanks.

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


RE: Windows 10 and PYODBC

2015-12-13 Thread William Abdo
Problem Resolved.
I have fixed the Oracle connection issue under Windows 10 with cx_Oracle .
PYODBC was only failing on the Oracle connection and worked fine on MS SQL 
under Windows 10.
Thank You for your time in this matter.

Respectfully,

William Abdo
Software App Engineer II
NTT America, an NTT Communications Company
Office:   +1 561.912.2434
Email:[email protected]
[https://rvip.team-center.net/externals/images/email/ntta.png]
[https://rvip.team-center.net/externals/images/email/ntta-twitter.png]
  [https://rvip.team-center.net/externals/images/email/ntta-linkedin.png] 
   
[https://rvip.team-center.net/externals/images/email/ntta-facebook.png] 
   
[https://rvip.team-center.net/externals/images/email/ntta-youtube.png] 








This email message is intended for the use of the person to whom it has been 
sent, and may contain information that is confidential or legally protected. If 
you are not the intended recipient or have received this message in error, you 
are not authorized to copy, distribute, or otherwise use this message or its 
attachments. Please notify the sender immediately by return e-mail and 
permanently delete this message and any attachments. NTT America makes no 
warranty that this email is error or virus free. Thank you.


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


Calling a list of functions

2015-12-13 Thread Ganesh Pal
Hi Team,

Iam on linux and python 2.7  . I have a bunch of functions  which I
have run sequentially .
I have put them in a list and Iam calling the functions in the list as
shown below ,  this works fine for me , please share your
opinion/views on the same


Sample code :

def print1():
print "one"

def print2():
print "two"

def print3():
print "three"

print_test = [print1(),print2(),print3()] //calling the function

for test in range(len(print_test)):
  try:
  print_test[test]
  except AssertionError as exc:


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


Re: Calling a list of functions

2015-12-13 Thread BartC

On 13/12/2015 17:26, Ganesh Pal wrote:


Iam on linux and python 2.7  . I have a bunch of functions  which I
have run sequentially .
I have put them in a list and Iam calling the functions in the list as
shown below ,  this works fine for me , please share your
opinion/views on the same


Sample code :

def print1():
 print "one"

def print2():
 print "two"

def print3():
 print "three"

print_test = [print1(),print2(),print3()] //calling the function

for test in range(len(print_test)):
   try:
   print_test[test]
   except AssertionError as exc:



> I have put them in a list and Iam calling the functions in the list as
> shown below ,  this works fine for me , please share your

That's not quite what the code does, which is to call the three 
functions and put their results into the list (3 Nones I think).


Then you evaluate each element of the list (a None each time).

I had to modify it to the following, which sets up a list of the three 
functions, then calls them in turn using the loop. I don't know what the 
'except' part was supposed to do:


def print1():
print "one"

def print2():
print "two"

def print3():
print "three"

print_test = [print1,print2,print3] #NOT calling the function

for test in range(len(print_test)):
try:
print_test[test]()  #calling the function
except AssertionError:
pass

The output of the two programs would have been the same I think.

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


Re: Calling a list of functions

2015-12-13 Thread Peter Otten
Ganesh Pal wrote:

> Hi Team,
> 
> Iam on linux and python 2.7  . I have a bunch of functions  which I
> have run sequentially .
> I have put them in a list and Iam calling the functions in the list as
> shown below ,  this works fine for me , please share your
> opinion/views on the same
> 
> 
> Sample code :
> 
> def print1():
> print "one"
> 
> def print2():
> print "two"
> 
> def print3():
> print "three"
> 
> print_test = [print1(),print2(),print3()] //calling the function

Python is not C++. In Python // is the integer division operator.
 
> for test in range(len(print_test)):
>   try:
>   print_test[test]
>   except AssertionError as exc:

1 Why range()? 

Iterate directly over the list:

for result in print_test:
print result

2 Why the try...except?

If there are functions in your actual code that may raise an AssertionError 
you won't catch it in the loop because you already invoked the functions 
when you built the list literal. To catch an exception like that you have to 
put the functions into the list, not the results:

functions = [print1, print2, print3]
for func in functions:
try:
print func()
except AssertionError:
pass

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


Re: Calling a list of functions

2015-12-13 Thread Ian Kelly
On Sun, Dec 13, 2015 at 10:26 AM, Ganesh Pal  wrote:
> Hi Team,
>
> Iam on linux and python 2.7  . I have a bunch of functions  which I
> have run sequentially .
> I have put them in a list and Iam calling the functions in the list as
> shown below ,  this works fine for me , please share your
> opinion/views on the same
>
>
> Sample code :
>
> def print1():
> print "one"
>
> def print2():
> print "two"
>
> def print3():
> print "three"
>
> print_test = [print1(),print2(),print3()] //calling the function

If I understand correctly, you want to build the list of functions and
then call them later. If so, this is not quite correct. This is
calling the functions at the time that you build the list and placing
the return values in the list, not the functions.

To build a list of the functions themselves, do:

print_test = [print1, print2, print3]

> for test in range(len(print_test)):

Iterating over range(len(something)) is usually not correct. Just
iterate over print_test instead. If you really need the indexes, then
iterate over enumerate(print_test).

>   try:
>   print_test[test]
>   except AssertionError as exc:

It looks like some code got cut off here since your exception handler
has no body. Regardless, the exception handler will never be invoked
because print_test[test] is just looking up the results of the
functions that were called when building the list.

To actually call the functions here instead of above, do:

for test in print_test:
test()
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Calling a list of functions

2015-12-13 Thread Grant Edwards
On 2015-12-13, Ganesh Pal  wrote:
> Hi Team,
>
> Iam on linux and python 2.7 . I have a bunch of functions which I
> have run sequentially . I have put them in a list and Iam calling the
> functions in the list as shown below , this works fine for me ,
> please share your opinion/views on the same
>
> Sample code :
>
> def print1():
> print "one"
>
> def print2():
> print "two"
>
> def print3():
> print "three"
>
> print_test = [print1(),print2(),print3()] //calling the function
>
> for test in range(len(print_test)):
>   try:
>   print_test[test]
>   except AssertionError as exc:

I have no clue what your actual goal is, but it might be better to do
the function call in the try/except block inside the loop. Otherwise
your try/except block makes no sense because there's nothing being
executed inside it:

for test in [print1,print2,print3]:
try:
test()
except AssertionError as exc:
print exc






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


Re: codecs.StreamRecoder not doing what I expected.

2015-12-13 Thread D'Arcy J.M. Cain
On Sun, 13 Dec 2015 13:17:24 +0100
Laura Creighton  wrote:
> In a message of Sun, 13 Dec 2015 01:35:45 -0500, "D'Arcy J.M. Cain"
> writes:
> >When I try to print it to the web page it fails because the \xe9
> >character is not valid ASCII.  However, my default encoding is utf-8.
> >Other web pages on the same server display fine.
> >
> >I have the following in the Apache config by the way.
> >
> >SetEnv PYTHONIOENCODING utf8
> >
> >So, my file is utf-8, I am reading it as utf-8, my Apache server
> >output is set to utf-8.  How is ASCII sneaking in?
> 
> What is your sys.stdout.encoding ?
> 
> just import sys and print the thing.
> 
> I think you will find that it is not what you expect.
> 
> Laura
> 

>>> print(sys.stdout.encoding)
utf8

That's what I was expecting.  However when I add that to my web log
output I get this:

get_recipe() PYTHONIOENCODING:  None
get_recipe() encoding:  646

Dang!  I was sure that I fixed that.  I have this in my Apache
configuration:

SetEnv PYTHONIOENCODING utf8

I guess I have an Apache problem now, not a Python one.  The strange
thing is that this was a fix for a similar problem I asked about and it
worked.  Isn't there some way that I can just set the default encoding
to utf8 for every Python program?  Googling suggests that I can't do
that but that doesn't see right.

Since utf8 includes ASCII why wouldn't it be the default anyway?

-- 
D'Arcy J.M. Cain
Vybe Networks Inc.
http://www.VybeNetworks.com/
IM:[email protected] VoIP: sip:[email protected]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python IO Redirection to Console

2015-12-13 Thread Terry Reedy

On 12/13/2015 9:14 AM, austin aigbe wrote:


I am trying to redirect the IO (stdout, stdin and stderr) to the console.


For a program run from the console, console IO is the default.  One must 
explicitly redirect to a file stream or pipe.  At least on Windows, 
console IO is also the default for a program run with subprocess. 
Again, anything else must explicitly given.


> Is there a Python module for this?

Unless I have completely misunderstood the question, not needed.

--
Terry Jan Reedy

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


Weird list conversion

2015-12-13 Thread high5storage
Hi all,

  f = open("stairs.bin", "rb") 
  data = list(f.read(16))
  print data

returns

['=', '\x04', '\x00', '\x05', '\x00', '\x01', '\x00', '\x00', '\x00', '\x00', 
'\x00', '\x00', '\x00', '\x00', '\x00', '\x00']

The first byte of the file is 0x3D according to my hex editor, so why does 
Python return '=' and not '\x3D'?

As always, thanks for any help!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Weird list conversion

2015-12-13 Thread Laura Creighton
In a message of Sun, 13 Dec 2015 11:45:19 -0800, [email protected] writes:
>Hi all,
>
>  f = open("stairs.bin", "rb") 
>  data = list(f.read(16))
>  print data
>
>returns
>
>['=', '\x04', '\x00', '\x05', '\x00', '\x01', '\x00', '\x00', '\x00', '\x00', 
>'\x00', '\x00', '\x00', '\x00', '\x00', '\x00']
>
>The first byte of the file is 0x3D according to my hex editor, so why does 
>Python return '=' and not '\x3D'?
>
>As always, thanks for any help!

0x3d is the ascii code for '='
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Weird list conversion

2015-12-13 Thread Ian Kelly
On Sun, Dec 13, 2015 at 12:45 PM,   wrote:
> Hi all,
>
>   f = open("stairs.bin", "rb")
>   data = list(f.read(16))
>   print data
>
> returns
>
> ['=', '\x04', '\x00', '\x05', '\x00', '\x01', '\x00', '\x00', '\x00', '\x00', 
> '\x00', '\x00', '\x00', '\x00', '\x00', '\x00']
>
> The first byte of the file is 0x3D according to my hex editor, so why does 
> Python return '=' and not '\x3D'?

They're equivalent representations of the same thing.

py> '\x3D'
'='
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Weird list conversion

2015-12-13 Thread KP
On Sunday, 13 December 2015 11:57:57 UTC-8, Laura Creighton  wrote:
> In a message of Sun, 13 Dec 2015 11:45:19 -0800, KP writes:
> >Hi all,
> >
> >  f = open("stairs.bin", "rb") 
> >  data = list(f.read(16))
> >  print data
> >
> >returns
> >
> >['=', '\x04', '\x00', '\x05', '\x00', '\x01', '\x00', '\x00', '\x00', 
> >'\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00']
> >
> >The first byte of the file is 0x3D according to my hex editor, so why does 
> >Python return '=' and not '\x3D'?
> >
> >As always, thanks for any help!
> 
> 0x3d is the ascii code for '='

I am aware of that - so is the rule that non-printables are returned in hex 
notation whereas printables come in their ASCII representation?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Weird list conversion

2015-12-13 Thread Erik

On 13/12/15 20:05, KP wrote:

On Sunday, 13 December 2015 11:57:57 UTC-8, Laura Creighton  wrote:

In a message of Sun, 13 Dec 2015 11:45:19 -0800, KP writes:

Hi all,

f = open("stairs.bin", "rb") data = list(f.read(16)) print data

returns

['=', '\x04', '\x00', '\x05', '\x00', '\x01', '\x00', '\x00',
'\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00']

The first byte of the file is 0x3D according to my hex editor, so
why does Python return '=' and not '\x3D'?

As always, thanks for any help!


0x3d is the ascii code for '='


I am aware of that - so is the rule that non-printables are returned
in hex notation whereas printables come in their ASCII
representation?


No, what is _returned_ is a list of one-byte strings.

When you call "print", then the list class's __repr__() method is called 
which in turn calls the contained objects' __repr__() methods in turn - 
it is those methods (in this case, they are all the string class's) 
which is deciding to render ASCII printable characters as just their 
value and ASCII non-printable characters using their hex notation.


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


Re: Weird list conversion

2015-12-13 Thread Ian Kelly
On Sun, Dec 13, 2015 at 1:05 PM, KP  wrote:
> On Sunday, 13 December 2015 11:57:57 UTC-8, Laura Creighton  wrote:
>> In a message of Sun, 13 Dec 2015 11:45:19 -0800, KP writes:
>> >Hi all,
>> >
>> >  f = open("stairs.bin", "rb")
>> >  data = list(f.read(16))
>> >  print data
>> >
>> >returns
>> >
>> >['=', '\x04', '\x00', '\x05', '\x00', '\x01', '\x00', '\x00', '\x00', 
>> >'\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00']
>> >
>> >The first byte of the file is 0x3D according to my hex editor, so why does 
>> >Python return '=' and not '\x3D'?
>> >
>> >As always, thanks for any help!
>>
>> 0x3d is the ascii code for '='
>
> I am aware of that - so is the rule that non-printables are returned in hex 
> notation whereas printables come in their ASCII representation?

What you're seeing there is the repr() of the string. The rule is that
it should be a printable representation that can be passed to eval to
reconstruct the string. The printable requirement means that NUL
should always come out escaped as '\x00' or perhaps '\0', but for
printable bytes escaping isn't necessary. I don't know if there's a
requirement that the repr of '\x3D' be '=', but it's probably the most
generally useful and I doubt that any implementation would depart from
that.

If you specifically want hex representations, then you could use hex(ord(foo)).

py> hex(ord('='))
'0x3d'
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Weird list conversion

2015-12-13 Thread Erik

On 13/12/15 20:28, Erik wrote:

When you call "print", then the list class's __repr__() method is called
which in turn calls the contained objects' __repr__() methods in turn


I mean the __str__() method, not __repr__() in this case - however, the 
answer is otherwise the same.


E.

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


Re: Weird list conversion

2015-12-13 Thread Larry Hudson via Python-list

On 12/13/2015 12:05 PM, KP wrote:

On Sunday, 13 December 2015 11:57:57 UTC-8, Laura Creighton  wrote:

In a message of Sun, 13 Dec 2015 11:45:19 -0800, KP writes:

Hi all,

  f = open("stairs.bin", "rb")
  data = list(f.read(16))
  print data

returns

['=', '\x04', '\x00', '\x05', '\x00', '\x01', '\x00', '\x00', '\x00', '\x00', 
'\x00', '\x00', '\x00', '\x00', '\x00', '\x00']

The first byte of the file is 0x3D according to my hex editor, so why does 
Python return '=' and not '\x3D'?

As always, thanks for any help!


0x3d is the ascii code for '='


I am aware of that - so is the rule that non-printables are returned in hex 
notation whereas printables come in their ASCII representation?


No.  The data is returned as raw bytes.
It's the print that is responsible for the way these bytes are _displayed_.

 -=- Larry -=-

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


Re: Weird list conversion

2015-12-13 Thread Chris Angelico
On Mon, Dec 14, 2015 at 7:31 AM, Erik  wrote:
> On 13/12/15 20:28, Erik wrote:
>>
>> When you call "print", then the list class's __repr__() method is called
>> which in turn calls the contained objects' __repr__() methods in turn
>
>
> I mean the __str__() method, not __repr__() in this case - however, the
> answer is otherwise the same.

It actually makes no difference; lists don't have __str__, and fall
back on object.__str__, which returns self.__repr__(). Inside
list.__repr__, the contained objects' reprs are combined. With lists,
you always get the repr. :)

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


Why is break allowed in finally, but continue is not?

2015-12-13 Thread Ned Batchelder
For testing coverage.py, I wrote a program to generate
randomly-structured Python functions.  When compiling
the results, I got a message I'd never seen before:

SyntaxError: 'continue' not supported inside 'finally' clause

I guess this makes sense, when cleaning up from an
exception, continuing the loop seems an odd thing to do.
But 'break' is allowed in 'finally' clauses!  I tried this:

# Huh? This prints "here", and no exception is raised.

for i in range(1):
try:
1/0
finally:
# If you change this to "continue", you get:
# 'continue' not supported inside 'finally' clause
break
print "here"

The finally is perfectly willing to have a 'break', but it's
a syntax error to have 'continue'?  Why? I don't see a
difference between the two when it comes to cleaning up
exceptions.

There are other things you can do in a finally clause that
will prevent the exception from being raised, like 'return',
and 'break' works just fine.

So why treat 'continue' specially?

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


Re: Why is break allowed in finally, but continue is not?

2015-12-13 Thread Ben Finney
Ned Batchelder  writes:

> For testing coverage.py, I wrote a program to generate
> randomly-structured Python functions.  When compiling
> the results, I got a message I'd never seen before:
>
> SyntaxError: 'continue' not supported inside 'finally' clause
>
> I guess this makes sense, when cleaning up from an
> exception, continuing the loop seems an odd thing to do.
> But 'break' is allowed in 'finally' clauses!  I tried this:
>
> # Huh? This prints "here", and no exception is raised.
>
> for i in range(1):
> try:
> 1/0
> finally:
> # If you change this to "continue", you get:
> # 'continue' not supported inside 'finally' clause
> break
> print "here"
>
> The finally is perfectly willing to have a 'break', but it's
> a syntax error to have 'continue'?  Why? I don't see a
> difference between the two when it comes to cleaning up
> exceptions.

Raymond Hettinger's answer is:

The use of continue in a finally-clause is forbidden because its
interpretation would have been problematic. […]


https://stackoverflow.com/questions/8302293/why-is-continue-not-allowed-in-a-finally-clause-in-python#answer-8302601>

The example he uses::

for i in range(10):
print i
try:
   raise RuntimeError
finally:
   continue# if the loop continues, what would happen to the 
exception?
print i

What, in your opinion, should the above code do if instead of ‘continue’
some other flow-control statement is used?

> There are other things you can do in a finally clause that
> will prevent the exception from being raised, like 'return',
> and 'break' works just fine.

Hettinger doesn't defend those, and is dubious about ‘return’'s
candidacy:

Interestingly, you can put a return inside a finally-clause and it
will swallow all exceptions including KeyboardInterrupt, SystemExit,
and MemoryError. That probably isn't a good idea either ;-)

> So why treat 'continue' specially?

I am inclined to agree, but in the opposite direction: a case should be
made for allowing *any* flow-control statement in an exception-handler's
‘finally’ clause.

-- 
 \ “We can't depend for the long run on distinguishing one |
  `\ bitstream from another in order to figure out which rules |
_o__)   apply.” —Eben Moglen, _Anarchism Triumphant_, 1999 |
Ben Finney

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


List of integers

2015-12-13 Thread KP


data = list(f.read(4))
print data

from a binary file might give

['\x10', '\x20', '\x12', '\x01']


How can I receive this instead?

[0x10, 0x20, 0x12, 0x01]

Thanks for all help!

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


Re: List of integers

2015-12-13 Thread Chris Angelico
On Mon, Dec 14, 2015 at 11:24 AM, KP  wrote:
> data = list(f.read(4))
> print data
>
> from a binary file might give
>
> ['\x10', '\x20', '\x12', '\x01']
>
>
> How can I receive this instead?
>
> [0x10, 0x20, 0x12, 0x01]
>
> Thanks for all help!

Try this:

data = [ord(x) for x in f.read(4)]

Note that it won't print out in hexadecimal.

>>> [0x10, 0x20, 0x12, 0x01]
[16, 32, 18, 1]

If you insist on that, try a subclass of int:

class ord(int):
ord = ord
def __new__(cls, x):
return super().__new__(cls, cls.ord(x))
def __repr__(self): return hex(self)

Then they'll come out in hex.

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


Help on class understanding in pymc code

2015-12-13 Thread Robert
Hi,

I follow code example at link:

https://users.obs.carnegiescience.edu/cburns/ipynbs/PyMC.html


There is the following code line:

sampler = pymc.MCMC([alpha,betax,betay,eps,model,tau,z_obs,x_true,y_true])


I want to know the detail of pymc.MCMC, then I get help content of it with:

/
help(pymc.MCMC)
Help on class MCMC in module pymc.MCMC:

class MCMC(pymc.Model.Sampler)
 |  This class fits probability models using Markov Chain Monte Carlo. Each 
stochastic variable
 |  is assigned a StepMethod object, which makes it take a single MCMC step 
conditional on the
 |  rest of the model. These step methods are called in turn.
 |  
 |>>> A = MCMC(input, db, verbose=0)
 |  
\\


help('pymc.Model.Sampler')
no Python documentation found for 'pymc.Model.Sampler'


help('pymc.Model')
Help on class Model in pymc:

pymc.Model = class Model(pymc.Container.ObjectContainer)
 |  The base class for all objects that fit probability models. Model is 
initialized with:
 |  
 |>>> A = Model(input, verbose=0)
 |  
 |:Parameters:
 |  - input : module, list, tuple, dictionary, set, object or nothing.
 |  Model definition, in terms of Stochastics, Deterministics, 
Potentials and Containers.
 |  If nothing, all nodes are collected from the base namespace.
 |  
 |  Attributes:
 |- deterministics
 |- stochastics (with observed=False)
 |- data (stochastic variables with observed=True)
 |- variables
 |- potentials
 |- containers
 |- nodes
 |- all_objects
 |- status: Not useful for the Model base class, but may be used by 
subclasses.
 |  
 |  The following attributes only exist after the appropriate method is called:
 |- moral_neighbors: The edges of the moralized graph. A dictionary, keyed 
by stochastic variable,
 |  whose values are sets of stochastic variables. Edges exist between the 
key variable and all variables
 |  in the value. Created by method _moralize.
 |- extended_children: The extended children of self's stochastic 
variables. See the docstring of
 |  extend_children. This is a dictionary keyed by stochastic variable.
 |- generations: A list of sets of stochastic variables. The members of 
each element only have parents in
 |  previous elements. Created by method find_generations.
 |  
 |  Methods:
 | - sample_model_likelihood(iter): Generate and return iter samples of 
p(data and potentials|model).
 |   Can be used to generate Bayes' factors.
 |  
 |  :SeeAlso: Sampler, MAP, NormalApproximation, weight, Container, graph.
 |  
 |  Method resolution order:
 |  Model
 |  pymc.Container.ObjectContainer
 |  pymc.six.NewBase
 |  pymc.Node.ContainerBase
 |  __builtin__.object
 |  
 |  Methods defined here:
 |  
 |  __init__(self, input=None, name=None, verbose=-1)
 |  Initialize a Model instance.
 |  
 |  :Parameters:
 |- input : module, list, tuple, dictionary, set, object or nothing.
 |Model definition, in terms of Stochastics, Deterministics, 
Potentials and Containers.
 |If nothing, all nodes are collected from the base namespace.
 |  
 |  draw_from_prior(self)
 |  Sets all variables to random values drawn from joint 'prior', meaning 
contributions
 |  of data and potentials to the joint distribution are not considered.
 |  
 |  get_node(self, node_name)
 |  Retrieve node with passed name
 |  
 |  seed(self)
 |  Seed new initial values for the stochastics.
 |  
 |  --
 |  Data descriptors defined here:
 |  
 |  generations
 |  
 |  --
 |  Data and other attributes defined here:
 |  
 |  __slotnames__ = []
 |  
 |  register = False
 |  
 |  --
 |  Methods inherited from pymc.Container.ObjectContainer:
 |  
 |  replace(self, item, new_container, key)
 |  
 |  --
 |  Data descriptors inherited from pymc.Container.ObjectContainer:
 |  
 |  value
 |  A copy of self, with all variables replaced by their values.
 |  
 |  --
 |  Methods inherited from pymc.Node.ContainerBase:
 |  
 |  assimilate(self, new_container)
 |  
 |  --
 |  Data descriptors inherited from pymc.Node.ContainerBase:
 |  
 |  __dict__
 |  dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |  list of weak references to the object (if defined)
 |  
 |  logp
 |  The summed log-probability of all stochastic variables (data
 |  or otherwise) and factor potentials in self.
 |  
 |  --
 |  Data and other attributes inherited from pymc.Node.Container

Re: Help on class understanding in pymc code

2015-12-13 Thread Peter Otten
Robert wrote:

> Hi,
> 
> I follow code example at link:
> 
> https://users.obs.carnegiescience.edu/cburns/ipynbs/PyMC.html
> 
> 
> There is the following code line:
> 
> sampler = pymc.MCMC([alpha,betax,betay,eps,model,tau,z_obs,x_true,y_true])
> 
> 
> I want to know the detail of pymc.MCMC, then I get help content of it
> with:
> 
> /
> help(pymc.MCMC)
> Help on class MCMC in module pymc.MCMC:
> 
> class MCMC(pymc.Model.Sampler)
>  |  This class fits probability models using Markov Chain Monte Carlo.
>  |  Each stochastic variable is assigned a StepMethod object, which makes
>  |  it take a single MCMC step conditional on the rest of the model. These
>  |  step methods are called in turn.
>  |  
>  |>>> A = MCMC(input, db, verbose=0)
>  |  
> \\
> 
> 
> help('pymc.Model.Sampler')
> no Python documentation found for 'pymc.Model.Sampler'
> 
> 
> help('pymc.Model')
> Help on class Model in pymc:
> 
> pymc.Model = class Model(pymc.Container.ObjectContainer)
>  |  The base class for all objects that fit probability models. Model is
>  |  initialized with:
>  |  
>  |>>> A = Model(input, verbose=0)
>  |  
>  |:Parameters:
>  |  - input : module, list, tuple, dictionary, set, object or nothing.
>  |  Model definition, in terms of Stochastics, Deterministics,
>  |  Potentials and Containers. If nothing, all nodes are collected
>  |  from the base namespace.
>  |  
>  |  Attributes:
>  |- deterministics
>  |- stochastics (with observed=False)
>  |- data (stochastic variables with observed=True)
>  |- variables
>  |- potentials
>  |- containers
>  |- nodes
>  |- all_objects
>  |- status: Not useful for the Model base class, but may be used by
>  |subclasses.
>  |  
>  |  The following attributes only exist after the appropriate method is
>  |  called:
>  |- moral_neighbors: The edges of the moralized graph. A dictionary,
>  |keyed by stochastic variable,
>  |  whose values are sets of stochastic variables. Edges exist between
>  |  the key variable and all variables in the value. Created by method
>  |  _moralize.
>  |- extended_children: The extended children of self's stochastic
>  |variables. See the docstring of
>  |  extend_children. This is a dictionary keyed by stochastic
>  |  variable.
>  |- generations: A list of sets of stochastic variables. The members
>  |of each element only have parents in
>  |  previous elements. Created by method find_generations.
>  |  
>  |  Methods:
>  | - sample_model_likelihood(iter): Generate and return iter samples
>  | of p(data and potentials|model).
>  |   Can be used to generate Bayes' factors.
>  |  
>  |  :SeeAlso: Sampler, MAP, NormalApproximation, weight, Container, graph.
>  |  
>  |  Method resolution order:
>  |  Model
>  |  pymc.Container.ObjectContainer
>  |  pymc.six.NewBase
>  |  pymc.Node.ContainerBase
>  |  __builtin__.object
>  |  
>  |  Methods defined here:
>  |  
>  |  __init__(self, input=None, name=None, verbose=-1)
>  |  Initialize a Model instance.
>  |  
>  |  :Parameters:
>  |- input : module, list, tuple, dictionary, set, object or
>  |nothing.
>  |Model definition, in terms of Stochastics, Deterministics,
>  |Potentials and Containers. If nothing, all nodes are
>  |collected from the base namespace.
>  |  
>  |  draw_from_prior(self)
>  |  Sets all variables to random values drawn from joint 'prior',
>  |  meaning contributions of data and potentials to the joint
>  |  distribution are not considered.
>  |  
>  |  get_node(self, node_name)
>  |  Retrieve node with passed name
>  |  
>  |  seed(self)
>  |  Seed new initial values for the stochastics.
>  |  
>  |  --
>  |  Data descriptors defined here:
>  |  
>  |  generations
>  |  
>  |  --
>  |  Data and other attributes defined here:
>  |  
>  |  __slotnames__ = []
>  |  
>  |  register = False
>  |  
>  |  --
>  |  Methods inherited from pymc.Container.ObjectContainer:
>  |  
>  |  replace(self, item, new_container, key)
>  |  
>  |  --
>  |  Data descriptors inherited from pymc.Container.ObjectContainer:
>  |  
>  |  value
>  |  A copy of self, with all variables replaced by their values.
>  |  
>  |  --
>  |  Methods inherited from pymc.Node.ContainerBase:
>  |  
>  |  assimilate(self, new_container)
>  |  
>  |  --
>  |  Data descriptors inherited from pymc.Node.ContainerBase:
>  |  
>  |  __dict__
>  |  dictionar

Re: Help on class understanding in pymc code

2015-12-13 Thread Robert
On Sunday, December 13, 2015 at 8:10:25 PM UTC-5, Peter Otten wrote:
> Robert wrote:
> 
> > Hi,
> > 
> > I follow code example at link:
> > 
> > https://users.obs.carnegiescience.edu/cburns/ipynbs/PyMC.html
> > 
> > 
> > There is the following code line:
> > 
> > sampler = pymc.MCMC([alpha,betax,betay,eps,model,tau,z_obs,x_true,y_true])
> > 
> > 
> > I want to know the detail of pymc.MCMC, then I get help content of it
> > with:
> > 
> > /
> > help(pymc.MCMC)
> > Help on class MCMC in module pymc.MCMC:
> > 
> > class MCMC(pymc.Model.Sampler)
> >  |  This class fits probability models using Markov Chain Monte Carlo.
> >  |  Each stochastic variable is assigned a StepMethod object, which makes
> >  |  it take a single MCMC step conditional on the rest of the model. These
> >  |  step methods are called in turn.
> >  |  
> >  |>>> A = MCMC(input, db, verbose=0)
> >  |  
> > \\
> > 
> > 
> > help('pymc.Model.Sampler')
> > no Python documentation found for 'pymc.Model.Sampler'
> > 
> > 
> > help('pymc.Model')
> > Help on class Model in pymc:
> > 
> > pymc.Model = class Model(pymc.Container.ObjectContainer)
> >  |  The base class for all objects that fit probability models. Model is
> >  |  initialized with:
> >  |  
> >  |>>> A = Model(input, verbose=0)
> >  |  
> >  |:Parameters:
> >  |  - input : module, list, tuple, dictionary, set, object or nothing.
> >  |  Model definition, in terms of Stochastics, Deterministics,
> >  |  Potentials and Containers. If nothing, all nodes are collected
> >  |  from the base namespace.
> >  |  
> >  |  Attributes:
> >  |- deterministics
> >  |- stochastics (with observed=False)
> >  |- data (stochastic variables with observed=True)
> >  |- variables
> >  |- potentials
> >  |- containers
> >  |- nodes
> >  |- all_objects
> >  |- status: Not useful for the Model base class, but may be used by
> >  |subclasses.
> >  |  
> >  |  The following attributes only exist after the appropriate method is
> >  |  called:
> >  |- moral_neighbors: The edges of the moralized graph. A dictionary,
> >  |keyed by stochastic variable,
> >  |  whose values are sets of stochastic variables. Edges exist between
> >  |  the key variable and all variables in the value. Created by method
> >  |  _moralize.
> >  |- extended_children: The extended children of self's stochastic
> >  |variables. See the docstring of
> >  |  extend_children. This is a dictionary keyed by stochastic
> >  |  variable.
> >  |- generations: A list of sets of stochastic variables. The members
> >  |of each element only have parents in
> >  |  previous elements. Created by method find_generations.
> >  |  
> >  |  Methods:
> >  | - sample_model_likelihood(iter): Generate and return iter samples
> >  | of p(data and potentials|model).
> >  |   Can be used to generate Bayes' factors.
> >  |  
> >  |  :SeeAlso: Sampler, MAP, NormalApproximation, weight, Container, graph.
> >  |  
> >  |  Method resolution order:
> >  |  Model
> >  |  pymc.Container.ObjectContainer
> >  |  pymc.six.NewBase
> >  |  pymc.Node.ContainerBase
> >  |  __builtin__.object
> >  |  
> >  |  Methods defined here:
> >  |  
> >  |  __init__(self, input=None, name=None, verbose=-1)
> >  |  Initialize a Model instance.
> >  |  
> >  |  :Parameters:
> >  |- input : module, list, tuple, dictionary, set, object or
> >  |nothing.
> >  |Model definition, in terms of Stochastics, Deterministics,
> >  |Potentials and Containers. If nothing, all nodes are
> >  |collected from the base namespace.
> >  |  
> >  |  draw_from_prior(self)
> >  |  Sets all variables to random values drawn from joint 'prior',
> >  |  meaning contributions of data and potentials to the joint
> >  |  distribution are not considered.
> >  |  
> >  |  get_node(self, node_name)
> >  |  Retrieve node with passed name
> >  |  
> >  |  seed(self)
> >  |  Seed new initial values for the stochastics.
> >  |  
> >  |  --
> >  |  Data descriptors defined here:
> >  |  
> >  |  generations
> >  |  
> >  |  --
> >  |  Data and other attributes defined here:
> >  |  
> >  |  __slotnames__ = []
> >  |  
> >  |  register = False
> >  |  
> >  |  --
> >  |  Methods inherited from pymc.Container.ObjectContainer:
> >  |  
> >  |  replace(self, item, new_container, key)
> >  |  
> >  |  --
> >  |  Data descriptors inherited from pymc.Container.ObjectContainer:
> >  |  
> >  |  value
> >  |  A copy of self, with all variables replaced by their values.
> >  |  
> >  |  ---

Re: Calling a list of functions

2015-12-13 Thread Steven D'Aprano
On Mon, 14 Dec 2015 04:26 am, Ganesh Pal wrote:

> Hi Team,
> 
> Iam on linux and python 2.7  . I have a bunch of functions  which I
> have run sequentially .
> I have put them in a list and Iam calling the functions in the list as
> shown below ,  this works fine for me , 

No it doesn't. It doesn't even compile -- it gives a SyntaxError because you
incorrectly use // as a comment deliminator instead of #. After fixing
that, you get a second SyntaxError because your code has an empty "except"
block. Obviously the code you show us is not the code you ran.

Why do people do this?

"Hi, here's a cake a made earlier, I think it tastes really nice. What do
you think?"

"That's not a cake. It's a bowl of mud with a cherry on top. Where is the
actual cake?"


-- 
Steven

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


Re: Calling a list of functions

2015-12-13 Thread Chris Angelico
On Mon, Dec 14, 2015 at 1:43 PM, Steven D'Aprano  wrote:
> Why do people do this?
>
> "Hi, here's a cake a made earlier, I think it tastes really nice. What do
> you think?"
>
> "That's not a cake. It's a bowl of mud with a cherry on top. Where is the
> actual cake?"

Steven, haven't you ever had a mudcake before?

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


Re: List of integers

2015-12-13 Thread KP
On Sunday, 13 December 2015 16:33:20 UTC-8, Chris Angelico  wrote:
> On Mon, Dec 14, 2015 at 11:24 AM, KP <> wrote:
> > data = list(f.read(4))
> > print data
> >
> > from a binary file might give
> >
> > ['\x10', '\x20', '\x12', '\x01']
> >
> >
> > How can I receive this instead?
> >
> > [0x10, 0x20, 0x12, 0x01]
> >
> > Thanks for all help!
> 
> Try this:
> 
> data = [ord(x) for x in f.read(4)]
> 
> Note that it won't print out in hexadecimal.
> 
> >>> [0x10, 0x20, 0x12, 0x01]
> [16, 32, 18, 1]
> 
> If you insist on that, try a subclass of int:
> 
> class ord(int):
> ord = ord
> def __new__(cls, x):
> return super().__new__(cls, cls.ord(x))
> def __repr__(self): return hex(self)
> 
> Then they'll come out in hex.
> 
> ChrisA

Thanks much!

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


Re: Calling a list of functions

2015-12-13 Thread Anand
On Sunday, December 13, 2015 at 9:26:52 AM UTC-8, Ganesh Pal wrote:
> Hi Team,
> 
> Iam on linux and python 2.7  . I have a bunch of functions  which I
> have run sequentially .
> I have put them in a list and Iam calling the functions in the list as
> shown below ,  this works fine for me , please share your
> opinion/views on the same
> 
> 
> Sample code :
> 
> def print1():
> print "one"
> 
> def print2():
> print "two"
> 
> def print3():
> print "three"
> 
> print_test = [print1(),print2(),print3()] //calling the function
> 
> for test in range(len(print_test)):
>   try:
>   print_test[test]
>   except AssertionError as exc:
> 
> 
> Regards,
> Ganesh




def print1(): 
 print "one" 
 
 def print2(): 
> print "two" 
> 
> def print3(): 
> print "three" 
> 
> print_test = [print1(),print2(),print3()] //calling the function 


If the idea is to have a 'pointers to function array' (as in C), you can do 
this:

fun_arr=[print1,print2,print3]
# Execute now
[ f() for f in fun_arr ]


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