Re: Writing game-state data...

2012-11-09 Thread Ian Kelly
On Fri, Nov 9, 2012 at 12:20 AM, Graham Fielding  wrote:

> file_object = open('savegame.sav', 'wb')

Here you open a file and assign it to "file_object".

> file['map'] = map

Here you attempt to write to "file" instead of "file_object".  "file"
is the name of a built-in type, hence your error message.

Since you seem to be trying to use shelve, you should also probably be
calling shelve.open to open the file, not just open.

> file['objects'] = objects
> file['player_index'] = objects.index(player)  #index of player in
> objects list
> file['inventory'] = inventory
> file['game_msgs'] = game_msgs
> file['game_state'] = game_state
> file['stairs_index'] = objects.index(stairs)
> file['dungeon_level'] = dungeon_level
> file.close()

Same issue for all these other statements.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: int.__init__ incompatible in Python 3.3

2012-11-09 Thread Ulrich Eckhardt

Am 08.11.2012 21:29, schrieb Terry Reedy:

On Thu, Nov 8, 2012 at 8:55 AM, Ulrich Eckhardt
 wrote:

On 3.3, it gives me a "TypeError: object.__init__() takes no
parameters". To some extent, this makes sense to me, because the
int subobject is not initialized in __init__ but in __new__. As a
workaround, I can simple drop the parameter from the call.


Just drop the do-nothing call.


Wait: Which call exactly?

Do you suggest that I shouldn't override __init__? The problem is that I 
need to attach additional info to the int and that I just pass this to 
the class on contstruction.


Or, do you suggest I don't call super().__init__()? That would seem 
unclean to me.


Just for your info, the class mimics a C enumeration, roughly it looks 
like this:


  class Foo(int):
  def __init__(self, value, name):
  super(Foo, self).__init__(value)
  self.name = name

  def __str__(self):
  return self.name

  Foo.AVALUE = Foo(1, 'AVALUE')
  Foo.BVALUE = Foo(2, 'BVALUE')

Note that even though I derive from an immutable class, the resulting 
class is not formally immutable. Maybe exactly that is the thing that 
the developers did not want me to do? I didn't understand all the 
implications in the bug ticket you quoted, to be honest.


Thank you for your time!

Uli
--
http://mail.python.org/mailman/listinfo/python-list


Python3.3 str() bug?

2012-11-09 Thread Helmut Jarausch
Hi,

probably I'm missing something.

Using   str(Arg) works just fine if  Arg is a list.
But
  str([],encoding='latin-1')

gives the error
TypeError: coercing to str: need bytes, bytearray or buffer-like object, 
   list found

If this isn't a bug how can I use str(Arg,encoding='latin-1') in general.
Do I need to flatten any data structure which is normally excepted by str() ?

Many thanks for a hint,
Helmut.

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


Re: Python3.3 str() bug?

2012-11-09 Thread Stefan Behnel
Helmut Jarausch, 09.11.2012 10:18:
> probably I'm missing something.
> 
> Using   str(Arg) works just fine if  Arg is a list.
> But
>   str([],encoding='latin-1')
> 
> gives the error
> TypeError: coercing to str: need bytes, bytearray or buffer-like object, 
>list found
> 
> If this isn't a bug how can I use str(Arg,encoding='latin-1') in general.
> Do I need to flatten any data structure which is normally excepted by str() ?

Funny idea to call this a bug in Python. What your code is asking for is to
decode the object you pass in using the "latin-1" encoding. Since a list is
not something that is "encoded", let alone in latin-1, you get an error,
and actually a rather clear one.

Note that this is not specific to Python3.3 or even 3.x. It's the same
thing in Py2 when you call the equivalent unicode() function.

Stefan


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


Re: Obnoxious postings from Google Groups

2012-11-09 Thread Hans Mulder
On 6/11/12 23:50:59, Steven D'Aprano wrote:
> On Tue, 06 Nov 2012 17:16:44 +, Prasad, Ramit wrote:
> 
>>> To enter the newline, I typed Ctrl-Q to tell bash to treat the next
>>> character as a literal, and then typed Ctrl-J to get a newline.
>>
>> That sounds complicated, my version of bash lets me type
>> 'foobar' for the same effect.
> 
> Well, I learned something new about bash.
> 
> On the other hand, the Ctrl-Q next-char-is-literal trick works for 
> entering control characters that otherwise don't have a key on the 
> keyboard.

How does that trick work?  If I need a control character
that is not available in my current keyboard mapping, how
would I enter such a character using this Ctrl-Q trick?


Just wondering,

-- HansM
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Right solution to unicode error?

2012-11-09 Thread wxjmfauth
Le jeudi 8 novembre 2012 21:42:58 UTC+1, Ian a écrit :
> On Thu, Nov 8, 2012 at 12:54 PM,   wrote:
> 
> > Font has nothing to do here.
> 
> > You are "simply" wrongly encoding your "unicode".
> 
> >
> 
>  '\u2013'
> 
> > '–'
> 
>  '\u2013'.encode('utf-8')
> 
> > b'\xe2\x80\x93'
> 
>  '\u2013'.encode('utf-8').decode('cp1252')
> 
> > '–'
> 
> 
> 
> No, it seriously is the font.  This is what I get using the default
> 
> ("Raster") font:
> 
> 
> 
> C:\>chcp 65001
> 
> Active code page: 65001
> 
> 
> 
> C:\>c:\python33\python
> 
> Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:55:48) [MSC v.1600
> 
> 32 bit (Intel)] on win32
> 
> Type "help", "copyright", "credits" or "license" for more information.
> 
> >>> '\u2013'
> 
> '–'
> 
> >>> import sys
> 
> >>> sys.stdout.buffer.write('\u2013\n'.encode('utf-8'))
> 
> –
> 
> 4
> 
> 
> 
> I should note here that the characters copied and pasted do not
> 
> correspond to the glyphs actually displayed in my terminal window.  In
> 
> the terminal window I actually see:
> 
> 
> 
> ΓÇô
> 
> 
> 
> If I change the font to Lucida Console and run the *exact same code*,
> 
> I get this:
> 
> 
> 
> C:\>chcp 65001
> 
> Active code page: 65001
> 
> 
> 
> C:\>c:\python33\python
> 
> Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:55:48) [MSC v.1600
> 
> 32 bit (Intel)] on win32
> 
> Type "help", "copyright", "credits" or "license" for more information.
> 
> >>> '\u2013'
> 
> '–'
> 
> 
> 
> >>> import sys
> 
> >>> sys.stdout.buffer.write('\u2013\n'.encode('utf-8'))
> 
> –
> 
> 4
> 
> 
> 
> Why is the font important?  I have no idea.  Blame Microsoft.

-

If you have something like this 'ΓÇô'; in
Unicode nomenclature:
>>> import unicodedata as ud
>>> for c in 'ΓÇô':
... ud.name(c)
... 
'GREEK CAPITAL LETTER GAMMA'
'LATIN CAPITAL LETTER C WITH CEDILLA'
'LATIN SMALL LETTER O WITH CIRCUMFLEX'

it is a sign of a "cp437" somewhere.

>>> '\u2013'.encode('utf-8').decode('cp437')
'ΓÇô'

On Windows 7. I do not remember having once a "coding
of the caracters" issue on XP.

jmf

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


RE: Writing game-state data...

2012-11-09 Thread Graham Fielding


 > To: [email protected]
> From: [email protected]
> Subject: Re: Writing game-state data...
> Date: Fri, 9 Nov 2012 07:37:56 +
> 
> On 09/11/2012 07:20, Graham Fielding wrote:
> >
> > Hey, folks, me again! I've been puzzling over this for a while now: I'm 
> > trying to write data to a file to save the state of my game using the 
> > following function: def save_game():
> >  #open a new empty shelve (possibly overwriting an old one) to write 
> > the game data
> >  file_object = open('savegame.sav', 'wb')
> >  file['map'] = map
> >  file['objects'] = objects
> >  file['player_index'] = objects.index(player)  #index of player in 
> > objects list
> >  file['inventory'] = inventory
> >  file['game_msgs'] = game_msgs
> >  file['game_state'] = game_state
> >  file['stairs_index'] = objects.index(stairs)
> >  file['dungeon_level'] = dungeon_level
> >  file.close() However, while 'savegame.sav' is created in the directory 
> > I specify, the function dies on file['map'] = map.  This is the end of the 
> > stack trace:
> >File "C:\Python Project\Roguelike.py", line 966, in save_game
> >  file['map'] = map
> > TypeError: 'type' object does not support item assignment Now, the map is 
> > randomly generated -- could that be an issue? Should I just scrap the 
> > current system and use pickle?  
> >
> 
> Please always give the complete stack trace, it's provided for a 
> purpose.  Here I'll grope around in the dark and guess that you need 
> file_object = shelve.open(...
> 
> -- 
> Cheers.
> 
> Mark Lawrence.
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list Here's the full stack 
> trace:   File "C:\Python Project\Roguelike.py", line 1048, in 
main_menu()
  File "C:\Python Project\Roguelike.py", line 1030, in main_menu
play_game()
  File "C:\Python Project\Roguelike.py", line 1007, in play_game
player_action = handle_keys()
  File "C:\Python Project\Roguelike.py", line 717, in handle_keys
quit_menu() #exit game
  File "C:\Python Project\Roguelike.py", line 698, in quit_menu
save_game()
  File "C:\Python Project\Roguelike.py", line 909, in save_game
file['map'] = map
TypeError: 'type' object does not support item assignment
>>>  What I'm trying to do is figure out a way to get the game to save its 
>>> state; I compiled it to an EXE using py2exe, but after that, the game 
>>> refuses to hold onto its data. Thanks for all the help! 
  -- 
http://mail.python.org/mailman/listinfo/python-list


RE: duck typing assert

2012-11-09 Thread Andriy Kornatskyy

Thank you for all comments.

> It makes very good sense to say:
>
> duckmatch(IFoo).compare(Foo)

Since we do duck match of IFoo... but there is no `duck match`, there is `duck 
test`. I believe instead of `compare` is more readable with `equals`. Than it 
is more from mathematics - precise answer... that you can not guarantee at all 
in dynamic programming language. So it false to use such wording to reflect 
this check. We can only make an assumption that one looks like the other 
(similar)... with some limitation of cause... understanding what is `duck test`.

http://en.wikipedia.org/wiki/Duck_test

The intent is to make such language `construct` so it reads as English sentence 
that make sense, and not mandatory `pythonic` way (readability counts, java 
smokes aside).

is_similar(Foo).to(IFoo) # <= but we lost `duck test` sense here?

Words `looks` and `like` are coming from duck test and point also direction:

# 1
looks(Foo).like(IFoo, notice=['__len__'], ignore_funcs=['foo'], 
ignore_argspec['bar'])

English sentence equivalent: if functions in Foo looks like one in IFoo than, 
probably, IFoo can be replaced with Foo; notice to check __len__, it is safe to 
ignore function `foo` and arguments passed to `bar`.

# 2
looks(Foo, notice=['__len__'], ignore_funcs=['foo'], 
ignore_argspec['bar']).like(IFoo)

English sentence equivalent: while looking at Foo notice to check `__len__`, it 
is safe to ignore function `foo` and arguments passed to `bar`, than probably 
it like IFoo.

I think #1 is easier to understand once it is written. Thoughts?

Also construction looks(Foo).like(IFoo) points direction of check. It you need 
the two be replaceable you need two asserts:

assert looks(Foo).like(IFoo)
assert looks(IFoo).like(Foo)

Thanks.

Andriy Kornatskyy



> Date: Fri, 9 Nov 2012 17:14:49 +1100
> Subject: Re: duck typing assert
> From: [email protected]
> To: [email protected]
>
> On Fri, Nov 9, 2012 at 12:00 PM, Ian Kelly  wrote:
> > looks(Foo).like(IFoo), on the other hand, is crystal clear about which
> > argument is which.
>
> I'm not so sure that it is, tbh. If you read it like an English
> sentence, it's clearly testing whether Foo matches the template in
> IFoo, but which are you more likely to do: test one class to see if it
> satisfies lots of templates, or test one template against every class
> you meet? I think probably the latter is, if not more likely than the
> former, at least sufficiently plausible as to create confusion. It
> makes very good sense to say:
>
> duckmatch(IFoo).compare(Foo)
>
> ie with the arguments the other way.
>
> ChrisA
> --
> http://mail.python.org/mailman/listinfo/python-list
  
-- 
http://mail.python.org/mailman/listinfo/python-list


Relative imports in packages

2012-11-09 Thread Johannes Bauer
Hi list,

I've these two minor problems which bothered me for quite some time,
maybe you can help me. I'm using Python 3.2.

For some project I have a component in its own package. Let's say the
structure looks like this:

pkg/__init__.py
pkg/Foo.py
pkg/Bar.py

Foo.py and Bar.py contain their classes "Foo" and "Bar", __init__.py
looks like this:

from .Foo import Foo
from .Bar import Bar

This allows me to "naturally" access classes, i.e. from my main program:

import pkg
pkg.Foo("initme")

or

from pkg import Foo
Foo("initme")

So far, so good. Now let's say Bar uses Foo, i.e. in Bar's header is
something like:

from .Foo import Foo

If this all weren't a package the declaration would just read "from Foo
import Foo" and I could easily append a small unit-test to Bar:

if __name__ == "__main__":
# test
pass

However, when using a package this fails: Obviously, when I directly go
into the pkg/ subdirectory and try to execute Bar.py, the import of Foo
fails and it doesn't work. Is there a nice solution to this or am I
doing it all wrong?

Then another minor question: Let's say my __init__.py contains a constant:

VERSION = "0.01"

>From my main program I can easily import that:

from pkg import VERSION
print(VERSION)

However, from Foo.py, I cannot seem to get the syntax right:

from . import VERSION

  File "Foo.py", line 10, in 
from . import VERSION
ImportError: cannot import name VERSION

How do I do this right?

Thanks for your advice,
Best regards,
Johannes

-- 
>> Wo hattest Du das Beben nochmal GENAU vorhergesagt?
> Zumindest nicht öffentlich!
Ah, der neueste und bis heute genialste Streich unsere großen
Kosmologen: Die Geheim-Vorhersage.
 - Karl Kaos über Rüdiger Thomas in dsa 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: error

2012-11-09 Thread inshu chauhan
http://www.ymlgroup.com/obscurehiddenlocation/downloads site, and
> imported  it using  from notzanzibar import DataType.
>

No i haven't downloaded it.. and this site is not opening...

>
> Then you'd have instantiated it in some code like
>   data = DataType(filename)
>
> and then the type of data would be notzanzibar.DataType  and the docs
> would be probably available somewhere on www.invalid.com/docs
>

This site is also blocked here.

>
> The only new guess:
>
> A 3D image would presumably have 3 subscripts, and you're only supplying
> two.
>

Yes a 3D image has 3 subscripts but m trying to access all three through
using only  2 subsscripts i.e X and Y


>
> If you want help, be explicit:
>
> 1) what version of CPython are you using, and on what OS?
>

I am using 2.7.3 on windows 7

2) what web site did you download some extra library from ?
>

The only extra libary i am using is Opencv , downloaded from
http://sourceforge.net/projects/opencvlibrary/



> 3) what import statement did you use ?
>

import cv

4) How are all those global variables initialized ?
>
see attached file

> 5) What command did you use to start the script ?  Did you run it from
> command.com, or from some IDE ?
>

Yes I am running it through IDLE GUI


> 5) Exactly what error message did you get, including the traceback ?
>

 Traceback (most recent call last):
  File "Z:\modules\Masking_an_image_dynamically.py", line 155, in 
AccessPixels(data)
  File "Z:\modules\.py", line 147, in AccessPixels
CreateMask(data, x, y)
  File "Z:\modules\new_classification.py", line 110, in CreateMask
point = data[iy, ix ]
error: index is out of range

The line numbers here and the file attached may be different because I have
removed a lot of print statements which I was using to debug the error..



> 6) What have you done to try to figure out your own error?
>

I have trying print out variables and Indices at each step..


Zero Piraeus : Where are you ?


Masking_an_image_dynamically.py
Description: Binary data
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python3.3 str() bug?

2012-11-09 Thread Helmut Jarausch
On Fri, 09 Nov 2012 10:37:11 +0100, Stefan Behnel wrote:

> Helmut Jarausch, 09.11.2012 10:18:
>> probably I'm missing something.
>> 
>> Using   str(Arg) works just fine if  Arg is a list.
>> But
>>   str([],encoding='latin-1')
>> 
>> gives the error
>> TypeError: coercing to str: need bytes, bytearray or buffer-like object, 
>>list found
>> 
>> If this isn't a bug how can I use str(Arg,encoding='latin-1') in general.
>> Do I need to flatten any data structure which is normally excepted by str() ?
> 
> Funny idea to call this a bug in Python. What your code is asking for is to
> decode the object you pass in using the "latin-1" encoding. Since a list is
> not something that is "encoded", let alone in latin-1, you get an error,
> and actually a rather clear one.
> 
> Note that this is not specific to Python3.3 or even 3.x. It's the same
> thing in Py2 when you call the equivalent unicode() function.
> 

For me it's not funny, at all.

Whenever Python3 encounters a bytestring it needs an encoding to convert it to
a string. If I feed a list of bytestrings or a list of list of bytestrings to 
'str' , etc, it should use the encoding for each bytestring component of the 
given data structure.

How can I convert a data strucure of arbitrarily complex nature, which contains
bytestrings somewhere, to a string?

This problem has arisen while converting a working Python2 script to Python3.3.
Since Python2 doesn't have bytestrings it just works.

Tell me how to convert  str(obj) from Python2 to Python3 if obj is an
arbitrarily complex data structure containing bytestrings somewhere 
which have to be converted to strings with a given encoding?

Helmut.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Obnoxious postings from Google Groups

2012-11-09 Thread Thomas Rachel

Am 31.10.2012 06:39 schrieb Robert Miles:


For those of you running Linux:  You may want to look into whether
NoCeM is compatible with your newsreader and your version of Linux.


This sounds as if it was intrinsically impossible to evaluate NoCeMs in 
Windows.


If someone writes a software for it, it can be run wherever desired.


Thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Obnoxious postings from Google Groups

2012-11-09 Thread Steven D'Aprano
On Fri, 09 Nov 2012 10:49:41 +0100, Hans Mulder wrote:

> On 6/11/12 23:50:59, Steven D'Aprano wrote:
>> On Tue, 06 Nov 2012 17:16:44 +, Prasad, Ramit wrote:
>> 
 To enter the newline, I typed Ctrl-Q to tell bash to treat the next
 character as a literal, and then typed Ctrl-J to get a newline.
>>>
>>> That sounds complicated, my version of bash lets me type
>>> 'foobar' for the same effect.
>> 
>> Well, I learned something new about bash.
>> 
>> On the other hand, the Ctrl-Q next-char-is-literal trick works for
>> entering control characters that otherwise don't have a key on the
>> keyboard.
> 
> How does that trick work?  If I need a control character that is not
> available in my current keyboard mapping, how would I enter such a
> character using this Ctrl-Q trick?

This only works if you are running a Linux or Unix shell with the 
libreadline library installed. This should work on nearly any modern 
Linux system with the bash shell. I don't know about other shells.

On Mac OS, the relevant library is called libedit instead, and the 
details may be different.

On Windows, you're out of luck.

Anyway, using Linux and bash: at the shell, if I type Ctrl-U, that is 
interpreted by the shell to mean "clear the line currently being edited". 
So if I type Ctrl-U, the line is cleared.

But if I type Ctrl-Q first, then Ctrl-U, instead readline enters a 
literal ^U character (ASCII value 0x15 = NAK Negative AcKnowledgment) 
into the line editing buffer.

The same trick should work in the Python interactive editor:

>>> ord('^U')  # type Ctrl-Q Ctrl-U to get the ^U char
21


Note that this may or may not work in IDEs such as IDLE. Many IDEs do 
their own thing for editing, and there's no guarantee they will support 
this functionality.

One last comment: readline is very configurable, and the command to 
insert the next character could be just about anything. But Ctrl-Q is the 
standard.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Obnoxious postings from Google Groups

2012-11-09 Thread Hans Mulder
On 7/11/12 01:13:47, Steven D'Aprano wrote:
> On Tue, 06 Nov 2012 23:08:11 +, Prasad, Ramit wrote:
> 
>> Steven D'Aprano wrote:
>>>
>>> On Tue, 06 Nov 2012 17:16:44 +, Prasad, Ramit wrote:
>>>
> To enter the newline, I typed Ctrl-Q to tell bash to treat the next
> character as a literal, and then typed Ctrl-J to get a newline.

 That sounds complicated, my version of bash lets me type
 'foobar' for the same effect.
>>>
>>> Well, I learned something new about bash.
>>>
>>> On the other hand, the Ctrl-Q next-char-is-literal trick works for
>>> entering control characters that otherwise don't have a key on the
>>> keyboard.
>>>
>>>
>> Would you mind elaborating on how this works? I know it's not a bash
>> list, but I do not understand how ctrl-J is considered a literal.
>> Obviously, I must have a different definition of "literal". Where can I
>> find a list of other literals? My Google-fu is being weak today. :(
> 
> I'm not an expert, so the following may not be exactly correct. As I 
> understand it, when you hit a key on the keyboard, it sends the character 
> you typed to the operating system. (The OS can then remap keys, generate 
> keyboard events including a timestamp, etc.)
> 
> Hit the J key, and the event includes character "j". Hit Shift-J, and 
> character "J" is sent. Hit Ctrl-J, and the character sent is the ASCII 
> control character ^J, or newline. (Technically, the name for ASCII 10 is 
> "linefeed" rather than "newline".)

Actually, the correct name for this character is OS-dependant:
The ASCII standard prescribes that if an OS chooses to use a
single character as its line terminator, then it must be this
one, and one should call it "newline".  Otherwise, it's name
is "linefeed".  So, the correct name is "newline" on Posix
system, but "linefeed" on Windows.


> Similarly, other control character combinations send other control codes:
> 
> ^A = ASCII 0x01 Start Of Heading
> ^L = ASCII 0xFF Formfeed \f
> ^M = ASCII 0x0D Carriage Return \r
> 
> etc.
> 
> http://en.wikipedia.org/wiki/C0_and_C1_control_codes
> 
> 
> When readline is enabled in bash, one of the standard editing commands is 
> that C-q (usually ctrl-Q on the keyboard) instructs readline to treat the 
> next key as a literal. So Ctrl-Q followed by Backspace won't delete the 
> previous character, but insert a literal DEL 0x7F character. 

It depends on what mode bash is in.  In Emacs mode, C-q works as you
describe, but in Vi mode you'd use C-v.

Doesn't everybody run bash in Vi mode :-?

> (One of those historical quirks is that on most(?) keyboards, the 
> Backspace key generates a DEL character rather than the ^H backspace 
> control code, and the Delete key generates an escape sequence. Go figure.)

Another quirk is that on most keyboards the "enter" key generates a
Carriage Return, which the terminal driver than converts to a Newline,
if icrlf mode is active.  (Shouldn't that be called "icrnl" mode?)


Hope this helps,

-- HansM

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


Re: int.__init__ incompatible in Python 3.3

2012-11-09 Thread Steven D'Aprano
On Fri, 09 Nov 2012 08:56:22 +0100, Ulrich Eckhardt wrote:

> Am 08.11.2012 21:29, schrieb Terry Reedy:
>> On Thu, Nov 8, 2012 at 8:55 AM, Ulrich Eckhardt
>>  wrote:
 On 3.3, it gives me a "TypeError: object.__init__() takes no
 parameters". To some extent, this makes sense to me, because the int
 subobject is not initialized in __init__ but in __new__. As a
 workaround, I can simple drop the parameter from the call.
>>
>> Just drop the do-nothing call.
> 
> Wait: Which call exactly?
> 
> Do you suggest that I shouldn't override __init__? The problem is that I
> need to attach additional info to the int and that I just pass this to
> the class on contstruction.

No, of course not. If you need to override __init__, you need to override 
__init__.


> Or, do you suggest I don't call super().__init__()? That would seem
> unclean to me.

On the contrary: calling super().__init__ when the superclass does 
something you don't want (i.e. raises an exception) is unclean.

Since the superclass __init__ does nothing, you don't need to call it. 
Only inherit behaviour that you actually *want*.

In Python 3.3:

py> class X(int):
... def __init__(self, *args):
... super().__init__(*args)  # does nothing, call it anyway
...
py> x = X(22)
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 3, in __init__
TypeError: object.__init__() takes no parameters


It is apparently an oversight, or a bug, that it ever worked in older 
versions.


> Note that even though I derive from an immutable class, the resulting
> class is not formally immutable. Maybe exactly that is the thing that
> the developers did not want me to do?

Nope, that's irrelevant. Attaching attributes to an otherwise immutable 
object is fine.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: error

2012-11-09 Thread inshu chauhan
I attached a wrong file...Right file is attached here


On Fri, Nov 9, 2012 at 11:53 AM, inshu chauhan wrote:

>
>
>
>
> http://www.ymlgroup.com/obscurehiddenlocation/downloads site, and
>> imported  it using  from notzanzibar import DataType.
>>
>
> No i haven't downloaded it.. and this site is not opening...
>
>>
>> Then you'd have instantiated it in some code like
>>   data = DataType(filename)
>>
>> and then the type of data would be notzanzibar.DataType  and the docs
>> would be probably available somewhere on www.invalid.com/docs
>>
>
> This site is also blocked here.
>
>>
>> The only new guess:
>>
>> A 3D image would presumably have 3 subscripts, and you're only supplying
>> two.
>>
>
> Yes a 3D image has 3 subscripts but m trying to access all three through
> using only  2 subsscripts i.e X and Y
>
>
>>
>> If you want help, be explicit:
>>
>> 1) what version of CPython are you using, and on what OS?
>>
>
> I am using 2.7.3 on windows 7
>
> 2) what web site did you download some extra library from ?
>>
>
> The only extra libary i am using is Opencv , downloaded from
> http://sourceforge.net/projects/opencvlibrary/
>
>
>
>> 3) what import statement did you use ?
>>
>
> import cv
>
> 4) How are all those global variables initialized ?
>>
> see attached file
>
>> 5) What command did you use to start the script ?  Did you run it from
>> command.com, or from some IDE ?
>>
>
> Yes I am running it through IDLE GUI
>
>
>> 5) Exactly what error message did you get, including the traceback ?
>>
>
>  Traceback (most recent call last):
>   File "Z:\modules\Masking_an_image_dynamically.py", line 155, in 
> AccessPixels(data)
>   File "Z:\modules\.py", line 147, in AccessPixels
> CreateMask(data, x, y)
>   File "Z:\modules\new_classification.py", line 110, in CreateMask
> point = data[iy, ix ]
>
> error: index is out of range
>
> The line numbers here and the file attached may be different because I
> have removed a lot of print statements which I was using to debug the
> error..
>
>
>
>> 6) What have you done to try to figure out your own error?
>>
>
> I have trying print out variables and Indices at each step..
>
>
> Zero Piraeus : Where are you ?
>
>
>


Masking_an_image_dynamically.py
Description: Binary data
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python3.3 str() bug?

2012-11-09 Thread Chris Angelico
On Fri, Nov 9, 2012 at 10:08 PM, Helmut Jarausch
 wrote:
> For me it's not funny, at all.

His description "funny" was in reference to the fact that you
described this as a bug. This is a heavily-used mature language; bugs
as fundamental as you imply are unlikely to exist (consequences of
design decisions there will be, but not outright bugs, usually);
extraordinary claims require extraordinary evidence.

> Whenever Python3 encounters a bytestring it needs an encoding to convert it to
> a string. If I feed a list of bytestrings or a list of list of bytestrings to
> 'str' , etc, it should use the encoding for each bytestring component of the
> given data structure.
>
> How can I convert a data strucure of arbitrarily complex nature, which 
> contains
> bytestrings somewhere, to a string?

Okay, now we're getting somewhere.

What you really should be doing is not transforming the whole
structure, but explicitly transforming each part inside it. I
recommend you stop fighting the language and start thinking about your
data as either *bytes* or *characters* and using the appropriate data
types (bytes or str) everywhere. You'll then find that it makes
perfect sense to explicitly translate (en/decode) from one to another,
but it doesn't make sense to encode a list in UTF-8 or decode a
dictionary from Latin-1.

> This problem has arisen while converting a working Python2 script to 
> Python3.3.
> Since Python2 doesn't have bytestrings it just works.

Actually it does; it just calls them "str". And there's a Unicode
string type, called "unicode", which is (more or less) the thing that
Python 3 calls "str".

You may be able to do some kind of recursive cast that, in one sweep
of your data structure, encodes all str objects into bytes using a
given encoding (or the reverse thereof). But I don't think this is the
best way to do things.

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


xml data or other?

2012-11-09 Thread Artie Ziff

Hello,

I want to process XML-like data like this:



ACPI (Advanced Control Power & Integration) testscript for 2.5 
kernels.

<\description>

ltp/testcases/kernel/device-drivers/acpi/ltpacpi.sh
<\test_location>
<\testname>


After manually editing the data above, the python module 
xml.etree.ElementTree parses it without failing due to error in the data 
structure.


Edits were substituting '/' for '\' on the end tags, and adding the 
following structure:




  
...
  <\testname>



Is there a name for the format above (perhaps xhtml)?
I'd like to find a python module that can translate it to proper xml. 
Does one exist? etree?


Many thanks!
az

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


Re: Python3.3 str() bug?

2012-11-09 Thread Helmut Jarausch
On Fri, 09 Nov 2012 23:22:04 +1100, Chris Angelico wrote:

> On Fri, Nov 9, 2012 at 10:08 PM, Helmut Jarausch
>  wrote:
>> For me it's not funny, at all.
> 
> His description "funny" was in reference to the fact that you
> described this as a bug. This is a heavily-used mature language; bugs
> as fundamental as you imply are unlikely to exist (consequences of
> design decisions there will be, but not outright bugs, usually);
> extraordinary claims require extraordinary evidence.

Just for the record.
I first discovered a real bug with Python3 when using os.walk on a file system
containing non-ascii characters in file names.

I encountered a very strange behavior (I still would call it a bug) when trying
to put non-ascii characters in email headers.
This has only been solved satisfactorily in Python3.3. 
> 
>> Whenever Python3 encounters a bytestring it needs an encoding to convert it 
>> to
>> a string. If I feed a list of bytestrings or a list of list of bytestrings to
>> 'str' , etc, it should use the encoding for each bytestring component of the
>> given data structure.
>>
>> How can I convert a data strucure of arbitrarily complex nature, which 
>> contains
>> bytestrings somewhere, to a string?
> 
> Okay, now we're getting somewhere.
> 
> What you really should be doing is not transforming the whole
> structure, but explicitly transforming each part inside it. I
> recommend you stop fighting the language and start thinking about your
> data as either *bytes* or *characters* and using the appropriate data
> types (bytes or str) everywhere. You'll then find that it makes
> perfect sense to explicitly translate (en/decode) from one to another,
> but it doesn't make sense to encode a list in UTF-8 or decode a
> dictionary from Latin-1.
> 
>> This problem has arisen while converting a working Python2 script to 
>> Python3.3.
>> Since Python2 doesn't have bytestrings it just works.
> 
> Actually it does; it just calls them "str". And there's a Unicode
> string type, called "unicode", which is (more or less) the thing that
> Python 3 calls "str".
> 
> You may be able to do some kind of recursive cast that, in one sweep
> of your data structure, encodes all str objects into bytes using a
> given encoding (or the reverse thereof). But I don't think this is the
> best way to do things.

Thanks, but in my case the (complex) object is returned via ctypes from the 
aspell library.
I still think that a standard function in Python3 which is able to 'stringify'
objects should take an encoding parameter.

Thanks,
Helmut.

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


Re: int.__init__ incompatible in Python 3.3

2012-11-09 Thread Ulrich Eckhardt

Am 09.11.2012 12:37, schrieb Steven D'Aprano:

On Fri, 09 Nov 2012 08:56:22 +0100, Ulrich Eckhardt wrote:

Or, do you suggest I don't call super().__init__()? That would seem
unclean to me.


On the contrary: calling super().__init__ when the superclass does
something you don't want (i.e. raises an exception) is unclean.

Since the superclass __init__ does nothing, you don't need to call it.
Only inherit behaviour that you actually *want*.



That one's hard to swallow for me, but maybe this is because I don't 
understand the Python object model sufficiently. The problem I have here 
is that not forwarding the __init__() to the baseclass could mean that 
necessary initializations are not performed, although in this very 
specify case I see that there aren't any. It still seems a bit like 
relying on an implementation details.


Anyhow, I'll have to do some more reading on the the construction of 
objects in Python, maybe then it'll all make sense. Until then, thanks 
everybody for nudging me in the right direction!


Uli

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


Re: duck typing assert

2012-11-09 Thread Steven D'Aprano
On Thu, 08 Nov 2012 18:00:58 -0700, Ian Kelly wrote:

> On Thu, Nov 8, 2012 at 4:33 PM, Steven D'Aprano
>  wrote:
>> On Thu, 08 Nov 2012 20:34:58 +0300, Andriy Kornatskyy wrote:
>>
>>> People who come from strongly typed languages that offer interfaces
>>> often are confused by lack of one in Python. Python, being dynamic
>>> typing programming language, follows duck typing principal. It can as
>>> simple as this:
>>>
>>> assert looks(Foo).like(IFoo)
>>
>> How very cute. And I don't mean that in a good way.
>>
>> Why is this a class with a method, instead of a function that takes two
>> class arguments (plus any optional arguments needed)?
>>
>> looks_like(Foo, IFoo)
>>
>> is less "cute", reads better to English speakers, and much more
>> Pythonic. This isn't Java, not everything needs to be a class.
> 
> I disagree.  Does that test whether Foo looks like IFoo, or IFoo looks
> like Foo? 

What's the difference? "Looks like" is a symmetric comparison, like 
"equal" and "almost equal", but not "subset", "less than" etc. If x looks 
like y, then necessarily y must look like x. If Katy Perry looks like 
Zooey Deschanel, then it stands to reason that Zooey Deschanel looks like 
Katy Perry. James Woods looks like Erwin Schroedinger, and Erwin 
Schroedinger looks like James Woods.

http://tvrefill.com/wp-content/uploads/2010/12/zooey-deschanel.jpg

http://cheezburger.com/6704400128


So in that sense, looks(Spam).like(Ham) must always be the same as 
looks(Ham).like(Spam), and the order of operators doesn't matter.

But that's not what we want! And to his credit, that's not what Andriy 
Kornatskyy's code actually implements. The problem is with the name, 
which is actively misleading by suggesting a symmetrical comparison for 
one which is not symmetrical.

Suppose we want to make a movie with Zooey Deschanel, but she's not 
available, so we want a replacement who is duck-type compatible with her. 
The replacement doesn't need to be a Deschanel sister, but she does need 
to do *at least* everything Zooey can do. If she can do more, that's 
fine, but she can't do less.

Since Katy Perry can do everything Zooey can do, PLUS she sings, we can 
replace Zooey with Katy: Katy is duck-type compatible with Zooey. But we 
can't replace Katy with Zooey, because Zooey can't sing.[1]

(I think... I really don't actually know if Zooey Deschanel can sing or 
not. Just go along with the example.)

The point I am making is that "looks like" is not a good description for 
this function. "Looks like" must be symmetrical, but the function we 
actually want is not symmetrical. It is actually a "subset" type 
relationship: given "looks(Zooey).like(Katy)", it checks that the public 
methods etc. of Zooey are a subset of the methods of Katy. That is, that 
instances of Katy can be used instead of instances of Zooey.

Or is it the other way? Damned if I know. Let's find out:

class Zooey:
def act(self): pass

class Katy:
def act(self): pass
def sing(self): pass


py> looks(Zooey).like(Katy)
__main__:2: UserWarning: 'sing': is missing.
False

I guessed wrong. The looks.like method as implemented tests that the 
right-hand size operand is a subset of the right-hand-side:

py> looks(Katy).like(Zooey)
True


I argue that this is the wrong way around. (Even if it isn't the wrong 
way around, it certainly isn't clear or obvious which way you have to 
write the operands!)

Consider this use-case:

candidates = [Hilary, Jennifer, Katy]
expected = looks(Zooey)  # instantiate the looks class once only
for actor in candidates:
if expected.like(actor):
make_movie_with(actor())


That's much nicer and more efficient than the way you have to write it 
now:

candidates = [Hilary, Jennifer, Katy]
for actor in candidates:
# instantiate the looks class every time we want to test another class
if looks(actor).like(Zooey):
make_movie_with(actor())


So... it's a cute name, that sounds English-like. But it doesn't actually 
describe what the function does, it is wasteful for at least one useful 
use-case, and it's not clear which order you have to supply the two 
arguments.


> looks(Foo).like(IFoo), on the other hand, is crystal clear about which
> argument is which.

I hope that by now you can see why I say that it is as clear as mud.





[1] Some people might argue that neither can Katy Perry.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: xml data or other?

2012-11-09 Thread rusi
On Nov 9, 5:54 pm, Artie Ziff  wrote:
> Hello,
>
> I want to process XML-like data like this:

> Edits were substituting '/' for '\' on the end tags, and adding the
> following structure:

If thats all you want, you can try the following:

# obviously this should come from a file
input= """

ACPI (Advanced Control Power & Integration) testscript
for 2.5 kernels.

<\description>

ltp/testcases/kernel/device-drivers/acpi/ltpacpi.sh
<\test_location>
<\testname>"""

prefix = """

"""

postfix = ""

correctedInput = prefix + input.replace("\\", "/") + postfix
# submit correctedinput to etree
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: error

2012-11-09 Thread inshu chauhan
Please Ignore the above two files attached,,, See this one


On Fri, Nov 9, 2012 at 12:47 PM, inshu chauhan wrote:

> I attached a wrong file...Right file is attached here
>
>
> On Fri, Nov 9, 2012 at 11:53 AM, inshu chauhan wrote:
>
>>
>>
>>
>>
>> http://www.ymlgroup.com/obscurehiddenlocation/downloads site, and
>>> imported  it using  from notzanzibar import DataType.
>>>
>>
>> No i haven't downloaded it.. and this site is not opening...
>>
>>>
>>> Then you'd have instantiated it in some code like
>>>   data = DataType(filename)
>>>
>>> and then the type of data would be notzanzibar.DataType  and the docs
>>> would be probably available somewhere on www.invalid.com/docs
>>>
>>
>> This site is also blocked here.
>>
>>>
>>> The only new guess:
>>>
>>> A 3D image would presumably have 3 subscripts, and you're only supplying
>>> two.
>>>
>>
>> Yes a 3D image has 3 subscripts but m trying to access all three through
>> using only  2 subsscripts i.e X and Y
>>
>>
>>>
>>> If you want help, be explicit:
>>>
>>> 1) what version of CPython are you using, and on what OS?
>>>
>>
>> I am using 2.7.3 on windows 7
>>
>> 2) what web site did you download some extra library from ?
>>>
>>
>> The only extra libary i am using is Opencv , downloaded from
>> http://sourceforge.net/projects/opencvlibrary/
>>
>>
>>
>>> 3) what import statement did you use ?
>>>
>>
>> import cv
>>
>> 4) How are all those global variables initialized ?
>>>
>> see attached file
>>
>>> 5) What command did you use to start the script ?  Did you run it from
>>> command.com, or from some IDE ?
>>>
>>
>> Yes I am running it through IDLE GUI
>>
>>
>>> 5) Exactly what error message did you get, including the traceback ?
>>>
>>
>>  Traceback (most recent call last):
>>   File "Z:\modules\Masking_an_image_dynamically.py", line 155, in 
>> AccessPixels(data)
>>   File "Z:\modules\.py", line 147, in AccessPixels
>> CreateMask(data, x, y)
>>   File "Z:\modules\new_classification.py", line 110, in CreateMask
>> point = data[iy, ix ]
>>
>> error: index is out of range
>>
>> The line numbers here and the file attached may be different because I
>> have removed a lot of print statements which I was using to debug the
>> error..
>>
>>
>>
>>> 6) What have you done to try to figure out your own error?
>>>
>>
>> I have trying print out variables and Indices at each step..
>>
>>
>> Zero Piraeus : Where are you ?
>>
>>
>>
>


Masking_an_image_dynamically.py
Description: Binary data
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: duck typing assert

2012-11-09 Thread Andriy Kornatskyy

1. In looks-like we check features of Foo (that may be superset) of what IFoo 
offers.

assert looks(Foo).like(IFoo)

2. We can check if Foo is limited to IFoo only:

assert looks(IFoo).like(Foo)

So it valid to have both asserts.

Thanks.

Andriy Kornatskyy



> From: [email protected]
> Subject: Re: duck typing assert
> Date: Fri, 9 Nov 2012 13:36:39 +
> To: [email protected]
>
> On Thu, 08 Nov 2012 18:00:58 -0700, Ian Kelly wrote:
>
> > On Thu, Nov 8, 2012 at 4:33 PM, Steven D'Aprano
> >  wrote:
> >> On Thu, 08 Nov 2012 20:34:58 +0300, Andriy Kornatskyy wrote:
> >>
> >>> People who come from strongly typed languages that offer interfaces
> >>> often are confused by lack of one in Python. Python, being dynamic
> >>> typing programming language, follows duck typing principal. It can as
> >>> simple as this:
> >>>
> >>> assert looks(Foo).like(IFoo)
> >>
> >> How very cute. And I don't mean that in a good way.
> >>
> >> Why is this a class with a method, instead of a function that takes two
> >> class arguments (plus any optional arguments needed)?
> >>
> >> looks_like(Foo, IFoo)
> >>
> >> is less "cute", reads better to English speakers, and much more
> >> Pythonic. This isn't Java, not everything needs to be a class.
> >
> > I disagree. Does that test whether Foo looks like IFoo, or IFoo looks
> > like Foo?
>
> What's the difference? "Looks like" is a symmetric comparison, like
> "equal" and "almost equal", but not "subset", "less than" etc. If x looks
> like y, then necessarily y must look like x. If Katy Perry looks like
> Zooey Deschanel, then it stands to reason that Zooey Deschanel looks like
> Katy Perry. James Woods looks like Erwin Schroedinger, and Erwin
> Schroedinger looks like James Woods.
>
> http://tvrefill.com/wp-content/uploads/2010/12/zooey-deschanel.jpg
>
> http://cheezburger.com/6704400128
>
>
> So in that sense, looks(Spam).like(Ham) must always be the same as
> looks(Ham).like(Spam), and the order of operators doesn't matter.
>
> But that's not what we want! And to his credit, that's not what Andriy
> Kornatskyy's code actually implements. The problem is with the name,
> which is actively misleading by suggesting a symmetrical comparison for
> one which is not symmetrical.
>
> Suppose we want to make a movie with Zooey Deschanel, but she's not
> available, so we want a replacement who is duck-type compatible with her.
> The replacement doesn't need to be a Deschanel sister, but she does need
> to do *at least* everything Zooey can do. If she can do more, that's
> fine, but she can't do less.
>
> Since Katy Perry can do everything Zooey can do, PLUS she sings, we can
> replace Zooey with Katy: Katy is duck-type compatible with Zooey. But we
> can't replace Katy with Zooey, because Zooey can't sing.[1]
>
> (I think... I really don't actually know if Zooey Deschanel can sing or
> not. Just go along with the example.)
>
> The point I am making is that "looks like" is not a good description for
> this function. "Looks like" must be symmetrical, but the function we
> actually want is not symmetrical. It is actually a "subset" type
> relationship: given "looks(Zooey).like(Katy)", it checks that the public
> methods etc. of Zooey are a subset of the methods of Katy. That is, that
> instances of Katy can be used instead of instances of Zooey.
>
> Or is it the other way? Damned if I know. Let's find out:
>
> class Zooey:
> def act(self): pass
>
> class Katy:
> def act(self): pass
> def sing(self): pass
>
>
> py> looks(Zooey).like(Katy)
> __main__:2: UserWarning: 'sing': is missing.
> False
>
> I guessed wrong. The looks.like method as implemented tests that the
> right-hand size operand is a subset of the right-hand-side:
>
> py> looks(Katy).like(Zooey)
> True
>
>
> I argue that this is the wrong way around. (Even if it isn't the wrong
> way around, it certainly isn't clear or obvious which way you have to
> write the operands!)
>
> Consider this use-case:
>
> candidates = [Hilary, Jennifer, Katy]
> expected = looks(Zooey) # instantiate the looks class once only
> for actor in candidates:
> if expected.like(actor):
> make_movie_with(actor())
>
>
> That's much nicer and more efficient than the way you have to write it
> now:
>
> candidates = [Hilary, Jennifer, Katy]
> for actor in candidates:
> # instantiate the looks class every time we want to test another class
> if looks(actor).like(Zooey):
> make_movie_with(actor())
>
>
> So... it's a cute name, that sounds English-like. But it doesn't actually
> describe what the function does, it is wasteful for at least one useful
> use-case, and it's not clear which order you have to supply the two
> arguments.
>
>
> > looks(Foo).like(IFoo), on the other hand, is crystal clear about which
> > argument is which.
>
> I hope that by now you can see why I say that it is as clear as mud.
>
>
>
>
>
> [1] Some people might argue that neither can Katy Perry.
>
>
> --
> Steven
> --
> http://mai

Re: error

2012-11-09 Thread inshu chauhan
Actually this one.. and its the last..


On Fri, Nov 9, 2012 at 2:59 PM, inshu chauhan  wrote:

> Please Ignore the above two files attached,,, See this one
>
>
> On Fri, Nov 9, 2012 at 12:47 PM, inshu chauhan wrote:
>
>> I attached a wrong file...Right file is attached here
>>
>>
>> On Fri, Nov 9, 2012 at 11:53 AM, inshu chauhan wrote:
>>
>>>
>>>
>>>
>>>
>>> http://www.ymlgroup.com/obscurehiddenlocation/downloads site, and
 imported  it using  from notzanzibar import DataType.

>>>
>>> No i haven't downloaded it.. and this site is not opening...
>>>

 Then you'd have instantiated it in some code like
   data = DataType(filename)

 and then the type of data would be notzanzibar.DataType  and the docs
 would be probably available somewhere on www.invalid.com/docs

>>>
>>> This site is also blocked here.
>>>

 The only new guess:

 A 3D image would presumably have 3 subscripts, and you're only supplying
 two.

>>>
>>> Yes a 3D image has 3 subscripts but m trying to access all three through
>>> using only  2 subsscripts i.e X and Y
>>>
>>>

 If you want help, be explicit:

 1) what version of CPython are you using, and on what OS?

>>>
>>> I am using 2.7.3 on windows 7
>>>
>>> 2) what web site did you download some extra library from ?

>>>
>>> The only extra libary i am using is Opencv , downloaded from
>>> http://sourceforge.net/projects/opencvlibrary/
>>>
>>>
>>>
 3) what import statement did you use ?

>>>
>>> import cv
>>>
>>> 4) How are all those global variables initialized ?

>>> see attached file
>>>
 5) What command did you use to start the script ?  Did you run it from
 command.com, or from some IDE ?

>>>
>>> Yes I am running it through IDLE GUI
>>>
>>>
 5) Exactly what error message did you get, including the traceback ?

>>>
>>>  Traceback (most recent call last):
>>>   File "Z:\modules\Masking_an_image_dynamically.py", line 155, in
>>> 
>>> AccessPixels(data)
>>>   File "Z:\modules\.py", line 147, in AccessPixels
>>> CreateMask(data, x, y)
>>>   File "Z:\modules\new_classification.py", line 110, in CreateMask
>>> point = data[iy, ix ]
>>>
>>> error: index is out of range
>>>
>>> The line numbers here and the file attached may be different because I
>>> have removed a lot of print statements which I was using to debug the
>>> error..
>>>
>>>
>>>
 6) What have you done to try to figure out your own error?

>>>
>>> I have trying print out variables and Indices at each step..
>>>
>>>
>>> Zero Piraeus : Where are you ?
>>>
>>>
>>>
>>
>


Masking_an_image_dynamically.py
Description: Binary data
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: duck typing assert

2012-11-09 Thread Chris Angelico
On Sat, Nov 10, 2012 at 1:01 AM, Andriy Kornatskyy
 wrote:
>
> 1. In looks-like we check features of Foo (that may be superset) of what IFoo 
> offers.
>
> assert looks(Foo).like(IFoo)
>
> 2. We can check if Foo is limited to IFoo only:
>
> assert looks(IFoo).like(Foo)
>
> So it valid to have both asserts.

You'll almost never need #2, but since there's no difference between a
"class" and an "interface", it's perfectly legal to switch them
around.

But I would generally expect that unrecognized methods are never a
problem (assuming they don't collide with anything) - that, as in
Steven's example, it's fine to have an actor who can sing when you
don't need her to. When you post job openings, you don't normally ask
for someone with "5+ years Python experience and unable to program in
REXX" [1]. You're checking for a minimum set of requirements.

[1] Though I suppose you might ask for someone who's unable to program
in Pascal. Might save you some hassle.

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


RE: duck typing assert

2012-11-09 Thread Andriy Kornatskyy

There is sense for #2. Let me explain. There is basic IFoo implementation and 
improved Foo. While I switched to Foo, I still want to be as close to IFoo as 
possible, since there might be sense to switch to Foo2 later, which conform to 
IFoo.

Here is the problem: if I will not assert #2 potentially I will use some 
`features` that are not in IFoo, thus that breaks my code switching to Foo2 
later.

That might not apply for 100% usability cases, just wanted to point that out as 
reasonable thing.

Thanks.

Andriy Kornatskyy



> Date: Sat, 10 Nov 2012 01:15:36 +1100
> Subject: Re: duck typing assert
> From: [email protected]
> To: [email protected]
>
> On Sat, Nov 10, 2012 at 1:01 AM, Andriy Kornatskyy
>  wrote:
> >
> > 1. In looks-like we check features of Foo (that may be superset) of what 
> > IFoo offers.
> >
> > assert looks(Foo).like(IFoo)
> >
> > 2. We can check if Foo is limited to IFoo only:
> >
> > assert looks(IFoo).like(Foo)
> >
> > So it valid to have both asserts.
>
> You'll almost never need #2, but since there's no difference between a
> "class" and an "interface", it's perfectly legal to switch them
> around.
>
> But I would generally expect that unrecognized methods are never a
> problem (assuming they don't collide with anything) - that, as in
> Steven's example, it's fine to have an actor who can sing when you
> don't need her to. When you post job openings, you don't normally ask
> for someone with "5+ years Python experience and unable to program in
> REXX" [1]. You're checking for a minimum set of requirements.
>
> [1] Though I suppose you might ask for someone who's unable to program
> in Pascal. Might save you some hassle.
>
> ChrisA
> --
> http://mail.python.org/mailman/listinfo/python-list
  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multi-dimensional list initialization

2012-11-09 Thread rusi
On Nov 9, 11:37 am, Steven D'Aprano  wrote:
> On Fri, 09 Nov 2012 17:07:09 +1100, Chris Angelico wrote:
> > On Fri, Nov 9, 2012 at 12:39 PM, Mark Lawrence 
> > wrote:
> >> On 07/11/2012 01:55, Steven D'Aprano wrote:
>
> >>> Who knows? Who cares? Nobody does:
>
> >>> n -= n
>
> >> But I've seen this scattered through code:
>
> >> x := x - x - x
>
> > Can you enlighten us as to how this is better than either:
> >  x := -x
> > or
> >  x := 0 - x
> > ? I'm not seeing it.
>
> I'm hoping that Mark intended it as an example of crappy code he has
> spotted in some other language rather than a counter-example of something
> you would do.
>
> To be pedantic... there may very well be some (rare) cases where you
> actually do want x -= x rather than just x = 0. Consider the case where x
> could be an INF or NAN. Then x -= x should give x = NAN rather than zero.
> That may be desirable in some cases.

In x86 assembler
mov ax, 0
is 4 bytes
sub ax, ax
is 2
and therefore better (at least for those brought up on Peter Norton);
the most common being
xor ax, ax
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multi-dimensional list initialization

2012-11-09 Thread Chris Angelico
On Sat, Nov 10, 2012 at 2:05 AM, rusi  wrote:
> In x86 assembler
> mov ax, 0
> is 4 bytes

Three bytes actually, B8 00 00 if my memory hasn't failed me. BA for
DX, B9 ought to be BX and BB CX, I think. But yes, the xor or sub is
two bytes and one clock.

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


[newbie] problem with module PyVisa

2012-11-09 Thread Jean Dubois
I'm trying to control a programmable power supply via USB using
python.
After doing some googling I thought I should use PyVisa for this
purpose, so I installed it as follows:
tar xvfz PyVISA-1.4.tar.gz
cd PyVISA-1.4
python setup.py install

Installation seems to finish without errors.

When I start a python session things go wrong as you can see in the
output below,
can anyone here tell me how to proceed correctly? thanks in advance.

>>> import visa
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/lib/python2.6/dist-packages/PyVISA-1.4-py2.6.egg/
visa.py", line 1, in 
from pyvisa.visa import *
  File "/usr/local/lib/python2.6/dist-packages/PyVISA-1.4-py2.6.egg/
pyvisa/visa.py", line 231, in 
resource_manager = ResourceManager()
  File "/usr/local/lib/python2.6/dist-packages/PyVISA-1.4-py2.6.egg/
pyvisa/vpp43.py", line 105, in __new__
it.init(*args, **kwds)
  File "/usr/local/lib/python2.6/dist-packages/PyVISA-1.4-py2.6.egg/
pyvisa/visa.py", line 227, in init
self.session = self.vi = vpp43.open_default_resource_manager()
  File "/usr/local/lib/python2.6/dist-packages/PyVISA-1.4-py2.6.egg/
pyvisa/vpp43.py", line 758, in open_default_resource_manager
visa_library().viOpenDefaultRM(byref(session))
  File "/usr/local/lib/python2.6/dist-packages/PyVISA-1.4-py2.6.egg/
pyvisa/vpp43.py", line 175, in __call__
self.load_library()
  File "/usr/local/lib/python2.6/dist-packages/PyVISA-1.4-py2.6.egg/
pyvisa/vpp43.py", line 146, in load_library
self.__lib = self.__cdecl_lib = cdll.LoadLibrary(path)
  File "/usr/lib/python2.6/ctypes/__init__.py", line 431, in
LoadLibrary
return self._dlltype(name)
  File "/usr/lib/python2.6/ctypes/__init__.py", line 353, in __init__
self._handle = _dlopen(self._name, mode)
OSError: /usr/local/vxipnp/linux/bin/libvisa.so.7: cannot open shared
object file: No such file or directory
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: int.__init__ incompatible in Python 3.3

2012-11-09 Thread Ian Kelly
On Fri, Nov 9, 2012 at 4:37 AM, Steven D'Aprano
 wrote:
> In Python 3.3:
>
> py> class X(int):
> ... def __init__(self, *args):
> ... super().__init__(*args)  # does nothing, call it anyway
> ...
> py> x = X(22)
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "", line 3, in __init__
> TypeError: object.__init__() takes no parameters
>
>
> It is apparently an oversight, or a bug, that it ever worked in older
> versions.

After reading through the bug history, I think that this change to int
is incorrect, or at least incomplete.  The goal of the change to
object.__init__ is to enable checking for unused arguments when doing
cooperative multiple inheritance, with the idea that each class in the
hierarchy will remove the arguments it uses and pass the rest along.
By the time object.__init__ is reached, any arguments remaining are
unused and extraneous.

In the case of int, int.__new__ takes up to two arguments.  Due to the
nature of the type system, these same two arguments are also passed to
int.__init__.  If each subclass removes its own arguments per the
convention, then by the time int.__init__ is reached, there are still
up to two *expected* arguments remaining.  It should not be the
responsibility of the subclasses (which one? all of them?) to remove
these arguments before calling super().__init__().  The int class
should have the responsibility of accepting and removing these two
arguments *and then* checking that there is nothing left over.

In Python 3.2, int.__init__ happily accepted the int arguments, but
also incorrectly accepted anything else you might pass to it, which
was suboptimal for cooperative multiple inheritance.  In Python 3.3,
it no longer accepts unused arguments, but it also rejects arguments
intended for its own class that it should accept, which as I see it
makes int.__init__ *unusable* for cooperative multiple inheritance.

I realize that the recommendation in the bug comments is to use
__new__ instead of __init__ for subclasses of immutable types.  But
then why have them call __init__ in the first place?  Why even fuss
over what arguments int.__init__ does or does not accept if we're not
supposed to be calling it at all?  And why is that deprecation not
mentioned anywhere in the documentation, that I can find?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [newbie] problem with module PyVisa

2012-11-09 Thread Rodrick Brown
It seems pretty obvious from the error. Try installing the missing lib packages.

OSError: /usr/local/vxipnp/linux/bin/libvisa.so.7: cannot open shared
object file: No such file or directory


Sent from my iPhone

On Nov 9, 2012, at 11:22 AM, Jean Dubois  wrote:

> OSError: /usr/local/vxipnp/linux/bin/libvisa.so.7: cannot open shared
> object file: No such file or directory
-- 
http://mail.python.org/mailman/listinfo/python-list


awk like usage in python

2012-11-09 Thread Rudra Banerjee
Friends,
I am in process learning python.
I basically use shell scripts for text formatting and trying my hand on
python.
where I am fighting is awk's functionality in python. 
Say, one of my real tiny code looks like:
#!/bin/bash
TMP=store
for i in $1/MnBi_EOS_*
do
#  echo $i
  grep -A 15 "T(est)" $i/out-Dy-eos2 >$TMP
  var_T=`awk '/T\(est\)/{printf $2}' $TMP`
  var_s1=`awk '/s1,torque/{print $6;exit}' $TMP`
  var_t=`awk '/s1,torque/{print $7;exit}' $TMP`
  echo  $var_T  $var_s1  $var_t >>tfl
#  echo ""
#  echo ""
done
sort -n tfl >$2
rm -i $TMP tfl

where the store looks like:
T(est)= 266.58K
TOTDOS= 0.48669E+02n_Ef= 0.62856E+02 Ebnd-0.11707E+02
 spec,subl=11N= 0.72132E+01s1c=-0.50284E+00
 spec,subl=11lined-up= 0.9E+00
 species,subl,cmp=111s1,torque= 0.59382E-02 0.36773E-04
 species,sublat,cmp=111sp-mom= 0.14449E+01
 species,sublat,cmp=111orbmom= 0.41075E-01
 species,subl,cmp=112s1,torque=-0.33939E-12 0.20885E-12
 species,sublat,cmp=112sp-mom= 0.54080E+00
 species,sublat,cmp=112orbmom= 0.14921E-01
 species,subl,cmp=113s1,torque= 0.60002E-02 0.15728E-02
 species,sublat,cmp=113sp-mom= 0.14448E+01
 species,sublat,cmp=113orbmom= 0.43989E-01
 spec,subl=12N= 0.72132E+01s1c=-0.50284E+00
 spec,subl=12lined-up= 0.9E+00
 species,subl,cmp=121s1,torque= 0.59378E-02 0.36850E-04

How can I import the awk functionality in python?

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


Re: duck typing assert‏

2012-11-09 Thread Terry Reedy

On 11/9/2012 1:30 AM, Steven D'Aprano wrote:

On Thu, 08 Nov 2012 23:44:54 -0500, Terry Reedy wrote:


On 11/8/2012 6:40 PM, Steven D'Aprano wrote:

[...]

IFoo.bar  # returns a computed property


Assuming IFoo is a class and bar is a property attribute of the class,
IFoo.bar is the property object itself, not the computed property of an
instance.


Given the context we were discussing, namely duck-typing, the examples I
gave should have been understood as indications, not literal code
snippets.


For the situation we are discussing, details matter. 'Indications' are 
not sufficient.



But in context, duck-typing classes normally is intended to substitute an
instance of one class for an instance of another class.


This we agree on.

> In that case, if

IFoo.bar is a property, and Foo.bar is a method, then you cannot
substitute an IFoo instance for a Foo instance, or vice versa:


If the property is properly written, this is wrong, as I showed in the 
working code you snipped and apparently ignored. Or at least you have 
not shown a problem with the code I posted.



ifoo = IFoo()
ifoo.bar  # returns a computed attribute


If the computed attribute is a method,
ifoo.bar()  # calls the method


foo = Foo()
foo.bar()  # calls the method



In the general case, you cannot use ifoo.bar() where foo.bar() is
expected, nor can you use foo.bar where ifoo.bar is expected.


In my actual code example, one can make the substitution in typical 
usage. 'In general', no substitution will work in all possible use 
cases, with unlimited introspection. But that is besides the point.


The point of duck typing is to worry about the details that matter and 
ignore the differences that do not matter. What matters in a specific 
case depend on the case. In many cases in Python, using isinstance, for 
instance, is looking too closely at details that do not matter. But in 
some cases, the actual class does matter and then we do use isinstance.



Suppose the expected interface is that instance.bar is a method that
takes no arguments.


This is exactly the situation for my code example. Here it is again:
---
from types import MethodType as bm

class C:
def __init__(self, x = 0):
self.x = x
def double(self):
return 2 * self.x

class Cp:
def __init__(self, x = 0):
self.x = x
@property
def double(self):
return bm(lambda self: 2 * self.x, self)

c, cp = C(3), Cp(3)

print(c.double, cp.double, c.double(), cp.double(), sep = '\n')
---
>>>
>
 of <__main__.Cp object at 0x03185A58>>
6
6
---

If the interface requires

isinstance(inst.double.__self__, C)  # or
inst.double.__func__.__name__ == 'double'

then cp is not a substitute for c. But we would normally consider that 
an over-specified interface.


> foo.bar() matches that interface, because bar is a

method. But ifoo.bar is a property.


Not in the sense that matters here. It is the result of calling the .get 
method of the Ifoo.bar property. If that result is a bound instance 
method, just as with foo.bar, then what is your problem with it, for the 
interface specified?


> Suppose it computes an int result.

If the object resulting from evaluating ifoo.bar does not match the 
expected interface, IT DOES NOT MATTER whether the object is the result 
of normal attribute access or of customized access via either 
__getattr__ or a property.


Anyway, I am supposing that Ifoo is written properly to match the 
expected interface. Here, that means that the property computes a bound 
method.


--
Terry Jan Reedy

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


Re: Python3.3 str() bug?

2012-11-09 Thread Stefan Behnel
Helmut Jarausch, 09.11.2012 14:13:
> On Fri, 09 Nov 2012 23:22:04 +1100, Chris Angelico wrote:
>> What you really should be doing is not transforming the whole
>> structure, but explicitly transforming each part inside it. I
>> recommend you stop fighting the language and start thinking about your
>> data as either *bytes* or *characters* and using the appropriate data
>> types (bytes or str) everywhere. You'll then find that it makes
>> perfect sense to explicitly translate (en/decode) from one to another,
>> but it doesn't make sense to encode a list in UTF-8 or decode a
>> dictionary from Latin-1.
>>
>>> This problem has arisen while converting a working Python2 script to 
>>> Python3.3.
>>> Since Python2 doesn't have bytestrings it just works.
>>
>> Actually it does; it just calls them "str". And there's a Unicode
>> string type, called "unicode", which is (more or less) the thing that
>> Python 3 calls "str".
>>
>> You may be able to do some kind of recursive cast that, in one sweep
>> of your data structure, encodes all str objects into bytes using a
>> given encoding (or the reverse thereof). But I don't think this is the
>> best way to do things.
> 
> Thanks, but in my case the (complex) object is returned via ctypes from the 
> aspell library.
> I still think that a standard function in Python3 which is able to 'stringify'
> objects should take an encoding parameter.

And how would that work? Would it recursively run through all data
structures you pass in or stop at some level or at some type of object?
Would it simply concatenate the substrings (and with what separator?), or
does the chaining depend on the objects found? Should it use the same
separator for everything or different separators for each level of the data
structure? Should it use str() for everything or repr() for some? Is str()
the right thing or are there special objects that need more than just a
call to str(), some kind of further preprocessing?

There are so many ways to do something like this, and it's so straight
forward to do in a given use case, that it's IMHO useless to even think
about adding a "general solution" for this to the stdlib.

Stefan


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


Printing characters outside of the ASCII range

2012-11-09 Thread danielk
I'm converting an application to Python 3. The app works fine on Python 2.

Simply put, this simple one-liner:

print(chr(254))

errors out with:

Traceback (most recent call last):
  File "D:\home\python\tst.py", line 1, in 
print(chr(254))
  File "C:\Python33\lib\encodings\cp437.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\xfe' in position 
0: character maps to 

I'm using this character as a delimiter in my application.

What do I have to do to convert this string so that it does not error out?
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Writing game-state data...

2012-11-09 Thread Prasad, Ramit
Graham Fielding wrote:
> 
> Hey, folks, me again!
> 
> I've been puzzling over this for a while now:
> 
> I'm trying to write data to a file to save the state of my game using the 
> following function:
> 
> def save_game():
>     #open a new empty shelve (possibly overwriting an old one) to write the 
> game data
>     file_object = open('savegame.sav', 'wb')
>     file['map'] = map
>     file['objects'] = objects
>     file['player_index'] = objects.index(player)  #index of player in objects 
> list
>     file['inventory'] = inventory
>     file['game_msgs'] = game_msgs
>     file['game_state'] = game_state
>     file['stairs_index'] = objects.index(stairs)
>     file['dungeon_level'] = dungeon_level
>     file.close()
> 
> However, while 'savegame.sav' is created in the directory I specify, the 
> function dies on file['map'] = map.
> This is the end of the stack trace:
> 
> 
>   File "C:\Python Project\Roguelike.py", line 966, in save_game
>     file['map'] = map
> TypeError: 'type' object does not support item assignment
> 

`file` is the built-in for file objects. I would say you need
to use file_object[] instead, but it is a file object
and is not meant for this usage. You can write directly
to a file but it is easier to use sqllite or shelve/pickle
libraries. I will use shelve in my example since your code
is already doing something similar. Do not forget to
import shelve in your own code.

def save():
shelf = shelve.open('savegame.sav', protocol=2) 
# Change pickle protocol if you use Python < 2.3
shelf['map'] = map
shelf['objects'] = objects
shelf['player_index'] = objects.index(player)
shelf['inventory'] = inventory
shelf['game_msgs'] = game_msgs
shelf['game_state'] = game_state
shelf['stairs_index'] = objects.index(stairs)
shelf['dungeon_level'] = dungeon_level
shelf.close()


> Now, the map is randomly generated -- could that be an issue?
> 

Both "file" and "map" are built-in keywords and using those
names for you own variables is called shadowing a built-in.
Shadowing a built-in can be interesting and useful but should
be avoided. Also, it seems like save() is not in a class nor
having anything passed in; are all the game states variables 
stored at the module level or something?

> Should I just scrap the current system and use pickle?

You are almost there, so I would not bother. Normally I would
use pickle over shelve; I have not needed any of the advantages 
of shelve and why use a library on top of pickle when I only
need pickle? Of course, YMMV.


~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python3.3 str() bug?

2012-11-09 Thread Ian Kelly
On Fri, Nov 9, 2012 at 2:18 AM, Helmut Jarausch
 wrote:
> Hi,
>
> probably I'm missing something.
>
> Using   str(Arg) works just fine if  Arg is a list.
> But
>   str([],encoding='latin-1')
>
> gives the error
> TypeError: coercing to str: need bytes, bytearray or buffer-like object,
>list found
>
> If this isn't a bug how can I use str(Arg,encoding='latin-1') in general.
> Do I need to flatten any data structure which is normally excepted by str() ?

In general, the __str__ implementations of complex data structures
will call repr() on their components, not str().  repr() normally does
not do any decoding in the first place and does not take an encoding
argument, so even if str([]) accepted an encoding, it wouldn't be
useful for anything.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Printing characters outside of the ASCII range

2012-11-09 Thread Ian Kelly
On Fri, Nov 9, 2012 at 10:17 AM, danielk  wrote:
> I'm converting an application to Python 3. The app works fine on Python 2.
>
> Simply put, this simple one-liner:
>
> print(chr(254))
>
> errors out with:
>
> Traceback (most recent call last):
>   File "D:\home\python\tst.py", line 1, in 
> print(chr(254))
>   File "C:\Python33\lib\encodings\cp437.py", line 19, in encode
> return codecs.charmap_encode(input,self.errors,encoding_map)[0]
> UnicodeEncodeError: 'charmap' codec can't encode character '\xfe' in position 
> 0: character maps to 
>
> I'm using this character as a delimiter in my application.
>
> What do I have to do to convert this string so that it does not error out?

In Python 2, chr(254) means the byte 254.

In Python 3, chr(254) means the Unicode character with code point 254,
which is "þ".  This character does not exist in CP 437, so it fails to
encode it for output.

If what you really want is the byte, then use b'\xfe' or bytes([254]) instead.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: duck typing assert

2012-11-09 Thread Prasad, Ramit
Andriy Kornatskyy wrote:
> 
> Thank you for all comments.
> 
> > It makes very good sense to say:
> >
> > duckmatch(IFoo).compare(Foo)
> 
> Since we do duck match of IFoo... but there is no `duck match`, there is 
> `duck test`. I believe instead of
> `compare` is more readable with `equals`. Than it is more from mathematics - 
> precise answer... that you can not
> guarantee at all in dynamic programming language. So it false to use such 
> wording to reflect this check. We can
> only make an assumption that one looks like the other (similar)... with some 
> limitation of cause...
> understanding what is `duck test`.
> 
> http://en.wikipedia.org/wiki/Duck_test
> 
> The intent is to make such language `construct` so it reads as English 
> sentence that make sense, and not
> mandatory `pythonic` way (readability counts, java smokes aside).
> 
> is_similar(Foo).to(IFoo) # <= but we lost `duck test` sense here?
> 
> Words `looks` and `like` are coming from duck test and point also direction:
> 
> # 1
> looks(Foo).like(IFoo, notice=['__len__'], ignore_funcs=['foo'], 
> ignore_argspec['bar'])
> 
> English sentence equivalent: if functions in Foo looks like one in IFoo than, 
> probably, IFoo can be replaced
> with Foo; notice to check __len__, it is safe to ignore function `foo` and 
> arguments passed to `bar`.
> 
> # 2
> looks(Foo, notice=['__len__'], ignore_funcs=['foo'], 
> ignore_argspec['bar']).like(IFoo)
> 
> English sentence equivalent: while looking at Foo notice to check `__len__`, 
> it is safe to ignore function `foo`
> and arguments passed to `bar`, than probably it like IFoo.

What about?

duck(Foo).equivalent_to(IFoo, ) 
duck(Foo).matches(IFoo, )

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Printing characters outside of the ASCII range

2012-11-09 Thread Andrew Berg
On 2012.11.09 11:17, danielk wrote:
> I'm converting an application to Python 3. The app works fine on Python 2.
> 
> Simply put, this simple one-liner:
> 
> print(chr(254))
> 
> errors out with:
> 
> Traceback (most recent call last):
>   File "D:\home\python\tst.py", line 1, in 
> print(chr(254))
>   File "C:\Python33\lib\encodings\cp437.py", line 19, in encode
> return codecs.charmap_encode(input,self.errors,encoding_map)[0]
> UnicodeEncodeError: 'charmap' codec can't encode character '\xfe' in position 
> 0: character maps to 
> 
> I'm using this character as a delimiter in my application.
> 
> What do I have to do to convert this string so that it does not error out?
> 
That character is outside of cp437 - the default terminal encoding on
many Windows systems. You will either need to change the code page to
something that supports the character (if you're going to change it, you
might as well change it to cp65001 since you are using 3.3), catch the
error and replace the character with something that is in the current
codepage (don't assume cp437; it is not the default everywhere), or use
a different character completely. If it works on Python 2, it's probably
changing the character automatically to a replacement character or you
were using IDLE, which is graphical and is not subject to the weird
encoding system of terminals.
-- 
CPython 3.3.0 | Windows NT 6.1.7601.17835
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Printing characters outside of the ASCII range

2012-11-09 Thread Dave Angel
On 11/09/2012 12:17 PM, danielk wrote:
> I'm converting an application to Python 3. The app works fine on Python 2.
>
> Simply put, this simple one-liner:
>
> print(chr(254))
>
> errors out with:
>
> Traceback (most recent call last):
>   File "D:\home\python\tst.py", line 1, in 
> print(chr(254))
>   File "C:\Python33\lib\encodings\cp437.py", line 19, in encode
> return codecs.charmap_encode(input,self.errors,encoding_map)[0]
> UnicodeEncodeError: 'charmap' codec can't encode character '\xfe' in position 
> 0: character maps to 
>
> I'm using this character as a delimiter in my application.
>
> What do I have to do to convert this string so that it does not error out?

What character do you want?  What characters do your console handle
directly?  What does a "delimiter" mean for your particular console?

Or are you just printing it for the fun of it, and the real purpose is
for further processing, which will not go to the console?

What kind of things will it be separating?  (strings, bytes ?)  Clearly
you originally picked it as something unlikely to occur in those elements.

When those things are combined with a separator between, how are the
results going to be used?  Saved to a file?  Printed to console?  What?

-- 

DaveA

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


RE: Python3.3 str() bug?

2012-11-09 Thread Prasad, Ramit
Chris Angelico wrote:
> 
> What you really should be doing is not transforming the whole
> structure, but explicitly transforming each part inside it. I
> recommend you stop fighting the language and start thinking about your
> data as either *bytes* or *characters* and using the appropriate data
> types (bytes or str) everywhere. You'll then find that it makes
> perfect sense to explicitly translate (en/decode) from one to another,
> but it doesn't make sense to encode a list in UTF-8 or decode a
> dictionary from Latin-1.
> 
[snip]
> 
> You may be able to do some kind of recursive cast that, in one sweep
> of your data structure, encodes all str objects into bytes using a
> given encoding (or the reverse thereof). But I don't think this is the
> best way to do things.

I would think the best way is to convert as you load the data.
That way everything is in the correct format as you manipulate
and generate new data.

 
~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: duck typing assert

2012-11-09 Thread Andriy Kornatskyy

duck(Foo).match(IFoo, )
duck(Foo).like(IFoo, )

Hm... function name in most cases is read as verb... this may cause confusion:
duck => synonyms => immerse, dip

Thanks.

Andriy Kornatskyy


> From: [email protected]
> To: [email protected]; [email protected]
> Subject: RE: duck typing assert
> Date: Fri, 9 Nov 2012 17:37:29 +
>
> Andriy Kornatskyy wrote:
> >
> > Thank you for all comments.
> >
> > > It makes very good sense to say:
> > >
> > > duckmatch(IFoo).compare(Foo)
> >
> > Since we do duck match of IFoo... but there is no `duck match`, there is 
> > `duck test`. I believe instead of
> > `compare` is more readable with `equals`. Than it is more from mathematics 
> > - precise answer... that you can not
> > guarantee at all in dynamic programming language. So it false to use such 
> > wording to reflect this check. We can
> > only make an assumption that one looks like the other (similar)... with 
> > some limitation of cause...
> > understanding what is `duck test`.
> >
> > http://en.wikipedia.org/wiki/Duck_test
> >
> > The intent is to make such language `construct` so it reads as English 
> > sentence that make sense, and not
> > mandatory `pythonic` way (readability counts, java smokes aside).
> >
> > is_similar(Foo).to(IFoo) # <= but we lost `duck test` sense here?
> >
> > Words `looks` and `like` are coming from duck test and point also direction:
> >
> > # 1
> > looks(Foo).like(IFoo, notice=['__len__'], ignore_funcs=['foo'], 
> > ignore_argspec['bar'])
> >
> > English sentence equivalent: if functions in Foo looks like one in IFoo 
> > than, probably, IFoo can be replaced
> > with Foo; notice to check __len__, it is safe to ignore function `foo` and 
> > arguments passed to `bar`.
> >
> > # 2
> > looks(Foo, notice=['__len__'], ignore_funcs=['foo'], 
> > ignore_argspec['bar']).like(IFoo)
> >
> > English sentence equivalent: while looking at Foo notice to check 
> > `__len__`, it is safe to ignore function `foo`
> > and arguments passed to `bar`, than probably it like IFoo.
>
> What about?
>
> duck(Foo).equivalent_to(IFoo, )
> duck(Foo).matches(IFoo, )
>
> This email is confidential and subject to important disclaimers and
> conditions including on offers for the purchase or sale of
> securities, accuracy and completeness of information, viruses,
> confidentiality, legal privilege, and legal entity disclaimers,
> available at http://www.jpmorgan.com/pages/disclosures/email.
  
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Multi-dimensional list initialization

2012-11-09 Thread Prasad, Ramit
Dennis Lee Bieber wrote:
> 
> On Fri, 9 Nov 2012 17:07:09 +1100, Chris Angelico 
> declaimed the following in gmane.comp.python.general:
> 
> > On Fri, Nov 9, 2012 at 12:39 PM, Mark Lawrence  
> > wrote:
> > > On 07/11/2012 01:55, Steven D'Aprano wrote:
> > >>
> > >>
> > >> Who knows? Who cares? Nobody does:
> > >>
> > >> n -= n
> > >>
> > >
> > > But I've seen this scattered through code:
> > >
> > > x := x - x - x
> >
> > Can you enlighten us as to how this is better than either:
> >  x := -x
> > or
> >  x := 0 - x
> 
>   Of course, if one has a language that, for some reason, evaluates
> right-to-left (APL, anyone), then
> 
>   x := x - x - x
> 
> becomes
> 
>   x := x - 0
> 

Is that not the same as x:=-x?


~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with module PyVisa

2012-11-09 Thread Jean Dubois
On 9 nov, 17:40, Rodrick Brown  wrote:
> It seems pretty obvious from the error. Try installing the missing lib 
> packages.
>
> OSError: /usr/local/vxipnp/linux/bin/libvisa.so.7: cannot open shared
> object file: No such file or directory
>
> Sent from my iPhone
>
> On Nov 9, 2012, at 11:22 AM, Jean Dubois  wrote:
>
>
>
>
>
>
>
> > OSError: /usr/local/vxipnp/linux/bin/libvisa.so.7: cannot open shared
> > object file: No such file or directory

The error may be obvious but finding this file and how to install it
is not unfortunately.
It seems I have to install it from the National Instruments site but
Debian Linux doesn't seem to be supported...
and I doubt whether just copying this file will be sufficient to make
PyVisa work.
I wonder whether there might be another way to communicate via USB
with a Keithley programmable power supply using Python.

best regards,
Jean



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


Re: How to print python commands automatically?

2012-11-09 Thread Peng Yu
> Is this what you want?
> http://docs.python.org/2/library/trace.html

I'm not able to get the mixing of the python command screen output on
stdout. Is there a combination of options for this purpose?

~/linux/test/python/man/library/trace$ cat main1.py
#!/usr/bin/env python

def f():
  print "Hello World!"

f()
~/linux/test/python/man/library/trace$ cat main.sh
#!/usr/bin/env bash

python -m trace --count -C . main1.py -t

~/linux/test/python/man/library/trace$ ./main.sh
Hello World!
~/linux/test/python/man/library/trace$ cat main1.cover
   #!/usr/bin/env python

1: def f():
1:   print "Hello World!"

1: f()



-- 
Regards,
Peng
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: problem with module PyVisa

2012-11-09 Thread Prasad, Ramit
Jean Dubois wrote:
> 
> On 9 nov, 17:40, Rodrick Brown  wrote:
> > It seems pretty obvious from the error. Try installing the missing lib 
> > packages.
> >
> > OSError: /usr/local/vxipnp/linux/bin/libvisa.so.7: cannot open shared
> > object file: No such file or directory
> >
> > Sent from my iPhone
> >
> > On Nov 9, 2012, at 11:22 AM, Jean Dubois  wrote:
> >
> > > OSError: /usr/local/vxipnp/linux/bin/libvisa.so.7: cannot open shared
> > > object file: No such file or directory
> 
> The error may be obvious but finding this file and how to install it
> is not unfortunately.
> It seems I have to install it from the National Instruments site but
> Debian Linux doesn't seem to be supported...
> and I doubt whether just copying this file will be sufficient to make
> PyVisa work.
> I wonder whether there might be another way to communicate via USB
> with a Keithley programmable power supply using Python.
> 

Here are some reference links that might help.
http://stackoverflow.com/questions/8140248/linux-implementation-of-visa-api
https://decibel.ni.com/content/message/37590


Hope that helps,
Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Printing characters outside of the ASCII range

2012-11-09 Thread danielk
On Friday, November 9, 2012 12:48:05 PM UTC-5, Dave Angel wrote:
> On 11/09/2012 12:17 PM, danielk wrote:
> 
> > I'm converting an application to Python 3. The app works fine on Python 2.
> 
> >
> 
> > Simply put, this simple one-liner:
> 
> >
> 
> > print(chr(254))
> 
> >
> 
> > errors out with:
> 
> >
> 
> > Traceback (most recent call last):
> 
> >   File "D:\home\python\tst.py", line 1, in 
> 
> > print(chr(254))
> 
> >   File "C:\Python33\lib\encodings\cp437.py", line 19, in encode
> 
> > return codecs.charmap_encode(input,self.errors,encoding_map)[0]
> 
> > UnicodeEncodeError: 'charmap' codec can't encode character '\xfe' in 
> > position 0: character maps to 
> 
> >
> 
> > I'm using this character as a delimiter in my application.
> 
> >
> 
> > What do I have to do to convert this string so that it does not error out?
> 
> 
> 
> What character do you want?  What characters do your console handle
> 
> directly?  What does a "delimiter" mean for your particular console?
> 
> 
> 
> Or are you just printing it for the fun of it, and the real purpose is
> 
> for further processing, which will not go to the console?
> 
> 
> 
> What kind of things will it be separating?  (strings, bytes ?)  Clearly
> 
> you originally picked it as something unlikely to occur in those elements.
> 
> 
> 
> When those things are combined with a separator between, how are the
> 
> results going to be used?  Saved to a file?  Printed to console?  What?
> 
> 
> 
> -- 
> 
> 
> 
> DaveA

The database I'm using stores information as a 3-dimensional array. The 
delimiters between elements are chr(252), chr(253) and chr(254). So a record 
can look like this (example only uses one of the delimiters for simplicity):

name + chr(254) + address + chr(254) + city + chr(254) + st + chr(254) + zip

The other delimiters can be embedded within each field. For example, if there 
were multiple addresses for 'name' then the 'address' field would look like 
this:

addr1 + chr(253) + addr2 + chr(253) + addr3 + etc ...

I use Python to connect to the database using subprocess.Popen to run a server 
process. Python requests 'actions' like 'read' and 'write' to the server 
process, whereby the server process performs the actions. Some actions require 
that the server send back information in the form of records that contain those 
delimiters.

I have __str__ and __repr__ methods in the classes but Python is choking on 
those characters. Surely, I could convert those characters on the server before 
sending them to Python and that is what I'm probably going to do, so guess I've 
answered my own question. On Python 2, it just printed the 'extended' ASCII 
representation.

I guess the question I have is: How do you tell Python to use a specific 
encoding for 'print' statements when I know there will be characters outside of 
the ASCII range of 0-127?

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


RE: How to print python commands automatically?

2012-11-09 Thread Prasad, Ramit
Peng Yu wrote:
> 
> > Is this what you want?
> > http://docs.python.org/2/library/trace.html
> 
> I'm not able to get the mixing of the python command screen output on
> stdout. Is there a combination of options for this purpose?
> 
> ~/linux/test/python/man/library/trace$ cat main1.py
> #!/usr/bin/env python
> 
> def f():
>   print "Hello World!"
> 
> f()
> ~/linux/test/python/man/library/trace$ cat main.sh
> #!/usr/bin/env bash
> 
> python -m trace --count -C . main1.py -t
> 
> ~/linux/test/python/man/library/trace$ ./main.sh
> Hello World!
> ~/linux/test/python/man/library/trace$ cat main1.cover
>#!/usr/bin/env python
> 
> 1: def f():
> 1:   print "Hello World!"
> 
> 1: f()
> 

Try with just --trace?


C:\ramit>python.exe -m trace test.py
C:\ramit\Python27\lib\trace.py: must specify one of --trace, --count, --report, 
--listfuncs, or --trackcalls

C:\ramit>python -m trace --trace test.py
 --- modulename: test, funcname: 
test.py(2): def f():
test.py(5): f()
 --- modulename: test, funcname: f
test.py(3): print "Hello World!"
Hello World!
 --- modulename: trace, funcname: _unsettrace
trace.py(80): sys.settrace(None)



~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Printing characters outside of the ASCII range

2012-11-09 Thread Prasad, Ramit
danielk wrote:
> 
> The database I'm using stores information as a 3-dimensional array. The 
> delimiters between elements are
> chr(252), chr(253) and chr(254). So a record can look like this (example only 
> uses one of the delimiters for
> simplicity):
> 
> name + chr(254) + address + chr(254) + city + chr(254) + st + chr(254) + zip
> 
> The other delimiters can be embedded within each field. For example, if there 
> were multiple addresses for 'name'
> then the 'address' field would look like this:
> 
> addr1 + chr(253) + addr2 + chr(253) + addr3 + etc ...
> 
> I use Python to connect to the database using subprocess.Popen to run a 
> server process. Python requests
> 'actions' like 'read' and 'write' to the server process, whereby the server 
> process performs the actions. Some
> actions require that the server send back information in the form of records 
> that contain those delimiters.
> 
> I have __str__ and __repr__ methods in the classes but Python is choking on 
> those characters. Surely, I could
> convert those characters on the server before sending them to Python and that 
> is what I'm probably going to do,
> so guess I've answered my own question. On Python 2, it just printed the 
> 'extended' ASCII representation.
> 
> I guess the question I have is: How do you tell Python to use a specific 
> encoding for 'print' statements when I
> know there will be characters outside of the ASCII range of 0-127?

You just need to change the string to one that is not 
trying to use the ASCII codec when printing. 

print(chr(253).decode('latin1')) # change latin1 to your 
 # chosen encoding.
ý


~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Printing characters outside of the ASCII range

2012-11-09 Thread Andrew Berg
On 2012.11.09 15:17, danielk wrote:
> I guess the question I have is: How do you tell Python to use a specific 
> encoding for 'print' statements when I know there will be characters outside 
> of the ASCII range of 0-127?
You don't. It's raising that exception because the terminal cannot
display that character, not because it's using the wrong encoding. As
Ian mentioned, chr() on Python 2 and chr() on Python 3 return two
different things. I'm not very familiar with the oddities of Python 2,
but I suspect sending bytes to the terminal could work since that is
what chr() on Python 2 returns.
-- 
CPython 3.3.0 | Windows NT 6.1.7601.17835
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Printing characters outside of the ASCII range

2012-11-09 Thread danielk
On Friday, November 9, 2012 4:34:19 PM UTC-5, Prasad, Ramit wrote:
> danielk wrote:
> 
> > 
> 
> > The database I'm using stores information as a 3-dimensional array. The 
> > delimiters between elements are
> 
> > chr(252), chr(253) and chr(254). So a record can look like this (example 
> > only uses one of the delimiters for
> 
> > simplicity):
> 
> > 
> 
> > name + chr(254) + address + chr(254) + city + chr(254) + st + chr(254) + zip
> 
> > 
> 
> > The other delimiters can be embedded within each field. For example, if 
> > there were multiple addresses for 'name'
> 
> > then the 'address' field would look like this:
> 
> > 
> 
> > addr1 + chr(253) + addr2 + chr(253) + addr3 + etc ...
> 
> > 
> 
> > I use Python to connect to the database using subprocess.Popen to run a 
> > server process. Python requests
> 
> > 'actions' like 'read' and 'write' to the server process, whereby the server 
> > process performs the actions. Some
> 
> > actions require that the server send back information in the form of 
> > records that contain those delimiters.
> 
> > 
> 
> > I have __str__ and __repr__ methods in the classes but Python is choking on 
> > those characters. Surely, I could
> 
> > convert those characters on the server before sending them to Python and 
> > that is what I'm probably going to do,
> 
> > so guess I've answered my own question. On Python 2, it just printed the 
> > 'extended' ASCII representation.
> 
> > 
> 
> > I guess the question I have is: How do you tell Python to use a specific 
> > encoding for 'print' statements when I
> 
> > know there will be characters outside of the ASCII range of 0-127?
> 
> 
> 
> You just need to change the string to one that is not 
> 
> trying to use the ASCII codec when printing. 
> 
> 
> 
> print(chr(253).decode('latin1')) # change latin1 to your 
> 
>  # chosen encoding.
> 
> ý
> 
> 
> 
> 
> 
> ~Ramit
> 
> 
> 
> 
> 
> This email is confidential and subject to important disclaimers and
> 
> conditions including on offers for the purchase or sale of
> 
> securities, accuracy and completeness of information, viruses,
> 
> confidentiality, legal privilege, and legal entity disclaimers,
> 
> available at http://www.jpmorgan.com/pages/disclosures/email.

D:\home\python>pytest.py
Traceback (most recent call last):
  File "D:\home\python\pytest.py", line 1, in 
print(chr(253).decode('latin1'))
AttributeError: 'str' object has no attribute 'decode'

Do I need to import something?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multi-dimensional list initialization

2012-11-09 Thread Ethan Furman

Prasad, Ramit wrote:

Dennis Lee Bieber wrote:

Of course, if one has a language that, for some reason, evaluates
right-to-left (APL, anyone), then

x := x - x - x

becomes

x := x - 0


Is that not the same as x:=-x?


No, its the same as 'x = x'.

~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list


Re: Printing characters outside of the ASCII range

2012-11-09 Thread Ian Kelly
On Fri, Nov 9, 2012 at 2:46 PM, danielk  wrote:
> D:\home\python>pytest.py
> Traceback (most recent call last):
>   File "D:\home\python\pytest.py", line 1, in 
> print(chr(253).decode('latin1'))
> AttributeError: 'str' object has no attribute 'decode'
>
> Do I need to import something?

Ramit should have written "encode", not "decode".  But the above still
would not work, because chr(253) gives you the character at *Unicode*
code point 253, not the character with CP437 ordinal 253 that your
terminal can actually print.  The Unicode equivalents of those
characters are:

>>> list(map(ord, bytes([252, 253, 254]).decode('cp437')))
[8319, 178, 9632]

So these are what you would need to encode to CP437 for printing.

>>> print(chr(8319))
ⁿ
>>> print(chr(178))
²
>>> print(chr(9632))
■

That's probably not the way you want to go about printing them,
though, unless you mean to be inserting them manually.  Is the data
you get from your database a string, or a bytes object?  If the
former, just do:

print(data.encode('cp437'))

If the latter, then it should be printable as is, unless it is in some
other encoding than CP437.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with module PyVisa

2012-11-09 Thread wrw
On Nov 9, 2012, at 3:43 PM, Jean Dubois  wrote:
> 
> The error may be obvious but finding this file and how to install it
> is not unfortunately.
> It seems I have to install it from the National Instruments site but
> Debian Linux doesn't seem to be supported...
> and I doubt whether just copying this file will be sufficient to make
> PyVisa work.
> I wonder whether there might be another way to communicate via USB
> with a Keithley programmable power supply using Python.
> 
> best regards,
> Jean
> 
> 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list

I've been using pyserial quite successfully to control a USB-to-serial 
converter.

That is, controlling a couple of RS232 serial devices via the USB port through 
a KeySpan USB-to-Serial converter.

Pyserial seems to make communication through the USB port quite transparent, at 
least on my OS-X system.

-Bill
-- 
http://mail.python.org/mailman/listinfo/python-list


fabric question

2012-11-09 Thread Jabba Laci
Hi,

I'm trying to use fabric to run a command on another Linux machine.
When I call "fab remote_info" (using the example from its
documentation), this is what I get:

local$ fab remote_info
[remote] Executing task 'remote_info'
[remote] run: uname -a
[remote] out: remote@path$

That is, it logs in successfully, but I get no output and I get a
prompt on the remote machine, i.e. it doesn't log out automatically
after calling the remote command. I also tried to specify the absolute
path of uname, same result. Any idea?

Thanks,

Laszlo
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to print python commands automatically?

2012-11-09 Thread Peng Yu
> Try with just --trace?
>
>
> C:\ramit>python.exe -m trace test.py
> C:\ramit\Python27\lib\trace.py: must specify one of --trace, --count, 
> --report, --listfuncs, or --trackcalls
>
> C:\ramit>python -m trace --trace test.py
>  --- modulename: test, funcname: 
> test.py(2): def f():
> test.py(5): f()
>  --- modulename: test, funcname: f
> test.py(3): print "Hello World!"
> Hello World!
>  --- modulename: trace, funcname: _unsettrace
> trace.py(80): sys.settrace(None)

I have to explicitly specify the modules I want to ignore. Is there a
way to ignore all the modules by default?

~/linux/test/python/man/library/trace/import$ cat.sh main.py main.sh test.py
==> main.py <==
#!/usr/bin/env python

import test

test.test()


==> main.sh <==
#!/usr/bin/env bash

python -m trace --trace main.py


==> test.py <==
def test1():
  print "Hello World!"

def test():
  test1()

~/linux/test/python/man/library/trace/import$ python -m trace --trace
--ignore-module=test main.py
 --- modulename: main, funcname: 
main.py(3): import test
main.py(5): test.test()
Hello World!
 --- modulename: trace, funcname: _unsettrace
trace.py(80): sys.settrace(None)


-- 
Regards,
Peng
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: fabric question

2012-11-09 Thread Miki Tebeka
> local$ fab remote_info
> [remote] Executing task 'remote_info'
> [remote] run: uname -a
> [remote] out: remote@path$

What happens when you ssh to the machine and run 'uname -a'?
(The out: ... is the output)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python3.3 str() bug?

2012-11-09 Thread Terry Reedy

On 11/9/2012 8:13 AM, Helmut Jarausch wrote:


Just for the record.
I first discovered a real bug with Python3 when using os.walk on a file system
containing non-ascii characters in file names.

I encountered a very strange behavior (I still would call it a bug) when trying
to put non-ascii characters in email headers.
This has only been solved satisfactorily in Python3.3.


Most bugs, such as the above, are in library modules. There have been 
many related to unicode. In my opinion, 3.3 is the first version to 
handle unicode decently well.



How can I convert a data strucure of arbitrarily complex nature, which contains
bytestrings somewhere, to a string?



Thanks, but in my case the (complex) object is returned via ctypes from the
aspell library.
I still think that a standard function in Python3 which is able to 'stringify'
objects should take an encoding parameter.


This is an interesting idea, which I have not seen before. It is more 
sensible in Python 3 than in Python 2. (For py2, unicode(str(object), 
encoding='xxx') does what you want.) Try presenting it here or on 
python-ideas as an enhancement request, rather than as a bug report ;-).


In the meanwhile, if you cannot have the object constructed with strings 
rather than bytes, I suggest you write a custom converter function that 
understands the structure and replaces bytes with strings.


--
Terry Jan Reedy

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


Re: how to get os.py to use an ./ntpath.py instead of Lib/ntpath.py

2012-11-09 Thread Aahz
In article ,
Thomas Rachel  
 wrote:
>Am 11.09.2012 05:46 schrieb Steven D'Aprano:
>>
>> Good for you. (Sorry, that comes across as more condescending than it is
>> intended as.) Monkey-patching often gets used for quick scripts and tiny
>> pieces of code because it works.
>>
>> Just beware that if you extend that technique to larger bodies of code,
>> say when using a large framework, or multiple libraries, your experience
>> may not be quite so good. Especially if *they* are monkey-patching too,
>> as some very large frameworks sometimes do. (Or so I am lead to believe.)
>
>This sonds like a good use case for a context manager, like the one in 
>decimal.Context.get_manager().

Note that because get_manager() applies to a specific Context instance it
is safe in a threaded application, which is NOT true for monkey-patching
modules even with a context manager.
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"Normal is what cuts off your sixth finger and your tail..."  --Siobhan
-- 
http://mail.python.org/mailman/listinfo/python-list


Is there a simpler way to modify all arguments in a function before using the arguments?

2012-11-09 Thread bruceg113355
Is there a simpler way to modify all arguments in a function before using the 
arguments?

For example, can the below code, in the modify arguments section be made into a 
few statements?  

def someComputation (aa, bb, cc, dd, ee, ff, gg, hh):
   # modify arguments
   # --
aa = aa.replace (“_” , “”)
bb=  bb.replace (“_” , “”)
cc = cc.replace (“_” , “”)
dd = dd.replace (“_” , “”)
ee = ee.replace (“_” , “”)
ff = ff.replace (“_” , “”)
gg = gg.replace (“_” , “”) 
hh = hh.replace (“_” , “”)

   # use the arguments
   # -
   # …

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


Re: Want to add dictionary keys to namespace?

2012-11-09 Thread Chris Angelico
On Sat, Nov 10, 2012 at 11:00 AM, Jeff Jeffries
 wrote:
> Smart people, Is there a way I can add a dictionaries keys to the python
> namespace? It would just be temporary as I am working with a large
> dictionary, and it would speed up work using an IDE.  I look and find
> nothing... none of the keys have spaces and none are common names within the
> module.
>
> #Do this?
> dictionary = {"AppleSeed": None, "Has": None,"Horrible" :None,"Art"}
> for key in dictionary.keys():
>  eval("%s=None"%key)

I would strongly recommend not.

> #or do this?
> locals().update(dictionary)

That doesn't work in a function, but outside of a function, you should
be able to use:

globals().update(dictionary)

However, I would advise using the dictionary explicitly. Give it a
shorter name and it'll be easier, but don't go for namespace
pollution. The PHP folks finally realized that register_globals is a
bad idea.

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


Re: Is there a simpler way to modify all arguments in a function before using the arguments?

2012-11-09 Thread Roy Smith
In article <[email protected]>,
 [email protected] wrote:

> Is there a simpler way to modify all arguments in a function before using the 
> arguments?
> 
> For example, can the below code, in the modify arguments section be made into 
> a few statements?  
> 
> def someComputation (aa, bb, cc, dd, ee, ff, gg, hh):
># modify arguments
># --
> aa = aa.replace (³_² , ³²)
> bb=  bb.replace (³_² , ³²)
> cc = cc.replace (³_² , ³²)
> dd = dd.replace (³_² , ³²)
> ee = ee.replace (³_² , ³²)
> ff = ff.replace (³_² , ³²)
> gg = gg.replace (³_² , ³²) 
> hh = hh.replace (³_² , ³²)
> 
># use the arguments
># -
># Š

You could do something like (not error checked)...

def someComputation(*args):
new_args = [arg.replace("_", "") for arg in args]
aa, bb, cc, dd, ee, ff, gg, hh = new_args

but that's pretty weird.  I suspect you just want to pass a list instead 
of a bunch of discrete arguments.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a simpler way to modify all arguments in a function before using the arguments?

2012-11-09 Thread Steven D'Aprano
On Fri, 09 Nov 2012 20:05:26 -0500, Roy Smith wrote:

> In article <[email protected]>,
>  [email protected] wrote:
> 
>> Is there a simpler way to modify all arguments in a function before
>> using the arguments?
>> 
>> For example, can the below code, in the modify arguments section be
>> made into a few statements?
>> 
>> def someComputation (aa, bb, cc, dd, ee, ff, gg, hh):
>># modify arguments
>># --
>> aa = aa.replace (³_² , ³²)
>> bb=  bb.replace (³_² , ³²)
>> cc = cc.replace (³_² , ³²)
>> dd = dd.replace (³_² , ³²)
>> ee = ee.replace (³_² , ³²)
>> ff = ff.replace (³_² , ³²)
>> gg = gg.replace (³_² , ³²)
>> hh = hh.replace (³_² , ³²)
>> 
>># use the arguments
>># -
>># Š
> 
> You could do something like (not error checked)...
> 
> def someComputation(*args):
> new_args = [arg.replace("_", "") for arg in args] aa, bb, cc, dd,
> ee, ff, gg, hh = new_args
> 
> but that's pretty weird.  I suspect you just want to pass a list instead
> of a bunch of discrete arguments.


I agree with everything you say except that it is pretty weird. As far as 
I am concerned, it isn't weird at all.

If you need named parameters:

def someComputation(aa, bb, cc, dd, ee, ff, gg, hh):
aa, bb, cc, dd, ee, ff, gg, hh = [arg.replace("_", "") 
for arg in (aa. bb, cc, dd, ee, ff, gg, hh)]
...



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a simpler way to modify all arguments in a function before using the arguments?

2012-11-09 Thread Paul Rubin
[email protected] writes:
> Is there a simpler way to modify all arguments in a function before
> using the arguments?

Why do you want to do that?

> For example, can the below code, in the modify arguments section be
> made into a few statements?

Whenever someone uses that many variables one always has to ask whether
a table would be better.  But, for

> def someComputation (aa, bb, cc, dd, ee, ff, gg, hh):
># modify arguments
># --
> aa = aa.replace (“_” , “”)
> bb=  bb.replace (“_” , “”)
> cc = cc.replace (“_” , “”)
> dd = dd.replace (“_” , “”)
> ee = ee.replace (“_” , “”)
> ff = ff.replace (“_” , “”)
> gg = gg.replace (“_” , “”) 
> hh = hh.replace (“_” , “”)

you could write (untested):

 def someComputation (aa, bb, cc, dd, ee, ff, gg, hh):
def modify(s): return s.replace('_', '')
aa,bb,cc,dd,ee,ff,gg,hh = \
map(modify,[aa,bb,cc,dd,ee,ff,gg,hh])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a simpler way to modify all arguments in a function before using the arguments?

2012-11-09 Thread Chris Angelico
On Sat, Nov 10, 2012 at 1:52 PM, Paul Rubin  wrote:
> [email protected] writes:
>> Is there a simpler way to modify all arguments in a function before
>> using the arguments?
>
> Why do you want to do that?
>

Contrived example:

def send_email(from, to, subj, body, whatever, other, headers, you, like):
# Okay, now translate all those into the appropriate encoding and
with special characters escaped
# We need to translate each one separately so that, for instance,
a newline in the subject won't let you create additional headers

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


Re: Is there a simpler way to modify all arguments in a function before using the arguments?

2012-11-09 Thread Paul Rubin
Chris Angelico  writes:
> Contrived example:
> def send_email(from, to, subj, body, whatever, other, headers, you, like):

That should be a dictionary with the header names as indexes.  In fact
there are already some email handling modules in the stdlib that
represent headers that way.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a simpler way to modify all arguments in a function before using the arguments?

2012-11-09 Thread Miki Tebeka
> Is there a simpler way to modify all arguments in a function before using the 
> arguments?
You can use a decorator:

from functools import wraps

def fix_args(fn):
@wraps(fn)
def wrapper(*args):
args = (arg.replace('_', '') for arg in args)
return fn(*args)

return wrapper

@fix_args
def foo(x, y):
print(x)
print(y)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Numpy combine channels

2012-11-09 Thread Aahz
In article ,
MRAB   wrote:
>On 10/09/2012 20:39, Wanderer wrote:
>>
>> I have an array generated by audiolab of left and right stereo
>> channels. It looks like [[1,1],[1,2],[2,3]]. I would like to combine
>> the left and right channels to get an array [2,3,5]. Is there a numpy
>> command to do that?
>
 import numpy
 numpy.array([[1,1],[1,2],[2,3]], dtype="i")
>array([[1, 1],
>[1, 2],
>[2, 3]])
 a[:, 0]
>array([1, 1, 2])
 a[:, 1]
>array([1, 2, 3])
 a[:, 0] + a[:, 1]
>array([2, 3, 5])
>
>But should they be added together to make mono?
>
>Suppose, for example, that both channels have a maximum value. Their
>sum would be _twice_ the maximum.
>
>Therefore, I think that it should probably be the average.
>
> >>> (a[:, 0] + a[:, 1]) / 2
>array([1, 1, 2])

I'd actually think it should be the max.  Consider a stereo where one
side is playing a booming bass while the other side is playing a rest
note -- should the mono combination be half as loud as as the bass?
-- 
Aahz ([email protected])   <*> http://www.pythoncraft.com/

"Normal is what cuts off your sixth finger and your tail..."  --Siobhan
-- 
http://mail.python.org/mailman/listinfo/python-list


skip Trackback error for ftp checking

2012-11-09 Thread moonhkt
HI All

How to skip Trackback warning/error when input ftp address is not
correct or reject ?

AIX 5.3

from ftplib import FTP
import ftplib
import sys
from optparse import OptionParser

parser = OptionParser()

parser.add_option("-a","--remote_host_address",
dest="remote_host_address",
help="REMOTE FTP HOST.",metavar="REMOTE FTP HOST")

parser.add_option("-u","--username", dest="username",
help="USERNAME for ftp sever.",metavar="USERNAME")

parser.add_option("-p","--password", dest="password",
help="PASSWORD for ftp server.",metavar="PASSWORD")

(options, args ) = parser.parse_args ()

if not (options.remote_host_address):
parser.error("REMOTE HOST are mandatory")

if options.username and not options.password:
parser.error("PASSWORD is mandatory if USERNAME is present")

try:
   ftp = FTP(options.remote_host_address)
except ftplib.error_perm,e:
   sys.exit(2)

if options.username:
   try:
  ftp.login(options.username,options.password)
   except ftplib.error_perm,e:
  print "Login failed: %s" % e
  sys.exit(1)
else:
   try:
  ftp.login()
   except ftplib.error_perm,e:
  print "Anonymous login failed: %s" % e
  sys.exit(1)
try:
print "LOGIN OK"
finally:
ftp.close()

Command line
---
chkftp.py -a teseting

Output as below

Traceback (most recent call last):
  File "...chkftp.py", line 33, in 
ftp = FTP(options.remote_host_address)
  File "/opt/freeware/lib/python2.6/ftplib.py", line 116, in __init__
self.connect(host)
  File "/opt/freeware/lib/python2.6/ftplib.py", line 131, in connect
self.sock = socket.create_connection((self.host, self.port),
self.timeout)
  File "/opt/freeware/lib/python2.6/socket.py", line 498, in
create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno 2] temporary failure in name resolution.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: skip Trackback error for ftp checking

2012-11-09 Thread Steven D'Aprano
On Fri, 09 Nov 2012 20:51:47 -0800, moonhkt wrote:

> HI All
> 
> How to skip Trackback warning/error when input ftp address is not
> correct or reject ?

The same way you would skip any other error when you do something wrong: 
catch the exception.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Obnoxious postings from Google Groups

2012-11-09 Thread Steven D'Aprano
On Fri, 09 Nov 2012 12:34:27 +0100, Hans Mulder wrote:

> On 7/11/12 01:13:47, Steven D'Aprano wrote:

>> Hit the J key, and the event includes character "j". Hit Shift-J, and
>> character "J" is sent. Hit Ctrl-J, and the character sent is the ASCII
>> control character ^J, or newline. (Technically, the name for ASCII 10
>> is "linefeed" rather than "newline".)
> 
> Actually, the correct name for this character is OS-dependant: The ASCII
> standard prescribes that if an OS chooses to use a single character as
> its line terminator, then it must be this one, and one should call it
> "newline".  Otherwise, it's name is "linefeed".  So, the correct name is
> "newline" on Posix system, but "linefeed" on Windows.

I find that hard to believe. Do you have a source for this claim?

The ASCII standard has nothing to do with operating systems. It is a 
character encoding system, whether you are using computers or notches 
carved into pieces of wood, you can encode characters to values using 
ASCII. ASCII is operating system agnostic.

Every source I have found describing the ASCII standard, and its 
equivalents from other standards bodies (e.g. ISO/IEC 646, EMCA 6) either 
directly refer to chr 10 as LF/Linefeed or refer back to the C0 control 
codes, which refers to it as LF/Linefeed.

For example:

http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-006.pdf

See also:

http://www.terena.org/activities/multiling/euroml/section04.html

which clearly shows char 10 as LF in all the given ISO 646 variants.

If you have a source for this claim, I would like to see it, otherwise I 
will stand by my claim that the standard name for ASCII char 10 is 
"linefeed".


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: awk like usage in python

2012-11-09 Thread Tim Roberts
Rudra Banerjee  wrote:
>
>Friends,
>I am in process learning python.
>I basically use shell scripts for text formatting and trying my hand on
>python.
>where I am fighting is awk's functionality in python. 
>Say, one of my real tiny code looks like:
>#!/bin/bash
>TMP=store
>for i in $1/MnBi_EOS_*
>do
>#  echo $i
>  grep -A 15 "T(est)" $i/out-Dy-eos2 >$TMP
>  var_T=`awk '/T\(est\)/{printf $2}' $TMP`
>  var_s1=`awk '/s1,torque/{print $6;exit}' $TMP`
>  var_t=`awk '/s1,torque/{print $7;exit}' $TMP`
>  echo  $var_T  $var_s1  $var_t >>tfl
>#  echo ""
>#  echo ""
>done
>sort -n tfl >$2
>rm -i $TMP tfl

Well, describe your program in words.  Then, you can convert it to Python.

For every directory in the given directory whose name starts with
MnBi_EOS_:
extract the 15 lines starting with T(est) from the file out-Dy-eos2 to
a temporary file
extract the 2nd field from the line with T(est) in it
extract the 6th field from the first line with "s1,torque"
extract the 7th field from the first line with "s1,torque"
print those three fields to a file
sort that file
-- 
Tim Roberts, [email protected]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list