strange comparison result with 'is'

2011-10-17 Thread Yingjie Lan
Hi all, 

This is quite strange when I used the Python shell with IDLE:

>>> x = []
>>> id(getattr(x, 'pop')) == id(x.pop)

True
>>> getattr(x, 'pop') is x.pop
False
>>> 

I suppose since the two things have the same id, the 'is'-test 
should give a True value, but I get a False value. 

Any particular reason for breaking this test?
I am quite confused as I show this before a large 
audience only to find the result denies my prediction.

The python version is 3.2.2; I am not sure about other versions.

Regards,

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


Message could not be delivered

2011-10-17 Thread Automatic Email Delivery Software
The original message was received at Mon, 17 Oct 2011 12:13:39 +0300
from python.org [153.233.80.188]

- The following addresses had permanent fatal errors -


- Transcript of session follows -
  while talking to python.org.:
>>> MAIL From:"Automatic Email Delivery Software" 
<<< 501 "Automatic Email Delivery Software" ... Refused



ÿþSmall Business Server has removed 
potentially unsafe e-mail attachment(s) 
from this message:

message.pif





Because computer viruses are commonly 
spread through files attached to e-mail 
messages, certain types of files will 
not be delivered to your mailbox. For 
more information, contact the person 
responsible for your network.

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


Re: strange comparison result with 'is'

2011-10-17 Thread Peter Otten
Yingjie Lan wrote:


> This is quite strange when I used the Python shell with IDLE:
> 
 x = []
 id(getattr(x, 'pop')) == id(x.pop)
> 
> True
 getattr(x, 'pop') is x.pop
> False

> 
> I suppose since the two things have the same id, the 'is'-test
> should give a True value, but I get a False value.
> 
> Any particular reason for breaking this test?
> I am quite confused as I show this before a large
> audience only to find the result denies my prediction.
> 
> The python version is 3.2.2; I am not sure about other versions.

The getattr() call is just a distraction. Every x.pop attribute access 
creates a new method object. In the case of

>>> x.pop is x.pop
False

they have to reside in memory simultaneously while in the expression

>>> id(x.pop) == id(x.pop)
True

a list.pop method object is created, its id() is taken (which is actually 
its address) and then the method object is released so that its memory 
address can be reused for the second x.pop. 

So in the latter case the two method objects can (and do) share the same 
address because they don't need to exist at the same time.

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


Re: strange comparison result with 'is'

2011-10-17 Thread Terry Reedy

On 10/17/2011 4:42 AM, Yingjie Lan wrote:

Hi all,

This is quite strange when I used the Python shell with IDLE:


Nothing to do with IDLE


 >>> x = []

>> id(getattr(x, 'pop')) == id(x.pop)

True
 >>> getattr(x, 'pop') is x.pop
False



I suppose since the two things have the same id, the 'is'-test
should give a True value, but I get a False value.


id and is are notorious for confusing beginners. You actually created 4 
bound method objects -- but not all at the same time. IDs only only 
unique among simultaneously existing objects. It is an accident of the 
CPython implementation that two of them have the same id, even though 
they are different objects. The second line is the correct one.



Any particular reason for breaking this test?
I am quite confused as I show this before a large
audience only to find the result denies my prediction.


Don't show this sort of thing. Name your objects so they do not get 
garbage collected in the middle of any demonstration.


--
Terry Jan Reedy

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


anagonda sucks )))))))))))))))

2011-10-17 Thread n v
http://123maza.com/48/silver424/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I get curses to work in Python 3.2 on win-64?

2011-10-17 Thread Jan Sundström
On 16 Okt, 06:59, Christoph Gohlke  wrote:
> On Oct 15, 1:13 pm, Jan Sundström  wrote:
>
>
>
> `import curses` should work. What exactly is the error message? Does
> `import curses` work outside your program/program directory?
>
> The curses package is part of the standard library and usually
> installed in Python32\Lib\curses. On Windows the  _curses.pyd files is
> missing in the standard distribution. curses-2.2.win-amd64-py3.2.exe
> installs the missing _curses.pyd file into Lib/site-packages.

Thanks for the tip to check in what library it works, that set me on
track tofind a silly mistake that I had done. Now everything works
fine.

But, how come that the Windows distribution for Python doesn't include
the _curses.pyd file?

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


Re: Loop through a dict changing keys

2011-10-17 Thread Gnarlodious
On Oct 15, 5:53 pm, PoD  wrote:

> data = {
>     'Mobile': 'string',
>     'context': '',
>     'order': '7',
>     'time': 'True'}
> types={'Mobile':str,'context':str,'order':int,'time':bool}
>
> for k,v in data.items():
>     data[k] = types[k](v)

Thanks for the tip, I didn't know you could do that. I ended up
filtering the values the bulky way, but it gives me total control over
what internet users feed my program.

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


Re: Loop through a dict changing keys

2011-10-17 Thread Chris Angelico
On Mon, Oct 17, 2011 at 5:20 AM, Gnarlodious  wrote:
> On Oct 15, 5:53 pm, PoD  wrote:
>
>> types={'Mobile':str,'context':str,'order':int,'time':bool}
>>
>> for k,v in data.items():
>>     data[k] = types[k](v)
>
> Thanks for the tip, I didn't know you could do that. I ended up
> filtering the values the bulky way, but it gives me total control over
> what internet users feed my program.

It should be noted that this will not in any way sanitize
data['context']. It calls the str() function on it, thus ensuring that
it's a string, but that's all. If you're needing to deal with
(potentially) malicious input, you'll want to swap in a function that
escapes it in some way (if it's going into a database, your database
engine will usually provide a 'quote' or 'escape' function; if it's to
go into a web page, I think cgi.escape is what you want).

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


Re: Equal sets with unequal print and str() representations

2011-10-17 Thread Westley Martínez
On Sun, Oct 16, 2011 at 05:52:03PM -0600, Ganesh Gopalakrishnan wrote:
> This probably is known, but a potential pitfall (was, for me)
> nevertheless. I suspect it is due to hash collisions between 's3'
> and 's13' in this case? It happens only rarely, depending on the
> contents of the set.
> 
> >>> S1 = {'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'}
> S1 = {'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'}
> >>> S2 = {'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'}
> S2 = {'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'}
> >>> S1
> S1
> {'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'}
> >>> S2
> S2
> {'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'}
> >>> S1==S2
> S1==S2
> True
> >>> str(S1)
> str(S1)
> "{'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'}"
> >>> str(S2)
> str(S2)
> "{'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'}"
> >>> str(S1) == str(S2)
> False

This is because sets do not preserve order.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I get curses to work in Python 3.2 on win-64?

2011-10-17 Thread Brian Curtin
On Sun, Oct 16, 2011 at 11:16, Jan Sundström  wrote:
> On 16 Okt, 06:59, Christoph Gohlke  wrote:
>> On Oct 15, 1:13 pm, Jan Sundström  wrote:
>>
>>
>>
>> `import curses` should work. What exactly is the error message? Does
>> `import curses` work outside your program/program directory?
>>
>> The curses package is part of the standard library and usually
>> installed in Python32\Lib\curses. On Windows the  _curses.pyd files is
>> missing in the standard distribution. curses-2.2.win-amd64-py3.2.exe
>> installs the missing _curses.pyd file into Lib/site-packages.
>
> Thanks for the tip to check in what library it works, that set me on
> track tofind a silly mistake that I had done. Now everything works
> fine.
>
> But, how come that the Windows distribution for Python doesn't include
> the _curses.pyd file?

It's not a standard library module on Windows. The curses Christoph
mentioned is built on the PDCurses library, which is an external
project.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Loop through a dict changing keys

2011-10-17 Thread 88888 dihedral
Uh, sounds reasonable, if one loops over an index variable  that could be 
altered during the loop execution then the loop may not end as expected.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strange comparison result with 'is'

2011-10-17 Thread Terry Reedy

On 10/17/2011 5:19 AM, Peter Otten wrote:


The getattr() call is just a distraction. Every x.pop attribute access
creates a new method object. In the case of


x.pop is x.pop

False

they have to reside in memory simultaneously while in the expression


id(x.pop) == id(x.pop)

True

a list.pop method object is created, its id() is taken (which is actually
its address) and then the method object is released so that its memory
address can be reused for the second x.pop.

So in the latter case the two method objects can (and do) share the same
address because they don't need to exist at the same time.


This has come up enough that I opened
http://bugs.python.org/issue13203
==
Newbies too often do something like (3.2.2, )

>>> id(getattr(x, 'pop')) == id(x.pop)
True

and get confused by the (invalid) result, whereas

>>> a,b=getattr(x, 'pop'),x.pop
>>> id(a)==id(b)
False

works properly. I think we should add a sentence or two or three to the 
id() doc, such as


Since a newly created argument object is either destroyed or becomes 
inaccessible before the function returns, *id(obj)* is only useful and 
valid if *obj* exists prior to the call and therefore after its return.
The value of an expression such as *id(666)== id(667)* is arbitrary and 
meaningless. The id of the first int object might or might not be reused 
for the second one.



With something like this added, we could just say 'read the id() doc'.

--
Terry Jan Reedy

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


Re: Loop through a dict changing keys

2011-10-17 Thread Ian Kelly
On Mon, Oct 17, 2011 at 10:21 AM, 8 dihedral
 wrote:
> Uh, sounds reasonable, if one loops over an index variable  that could be 
> altered during the loop execution then the loop may not end as expected.

>From the docs:  "Iterating views while adding or deleting entries in
the dictionary may raise a RuntimeError or fail to iterate over all
entries."

Changing the values of existing entries while iterating is considered
to be safe, though.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python.org appears to be down

2011-10-17 Thread Miki Tebeka
http://www.isup.me/python.org ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Loop through a dict changing keys

2011-10-17 Thread Steven D'Aprano
On Sun, 16 Oct 2011 11:20:49 -0700, Gnarlodious wrote:

> On Oct 15, 5:53 pm, PoD  wrote:
> 
>> data = {
>>     'Mobile': 'string',
>>     'context': '',
>>     'order': '7',
>>     'time': 'True'}
>> types={'Mobile':str,'context':str,'order':int,'time':bool}
>>
>> for k,v in data.items():
>>     data[k] = types[k](v)
> 
> Thanks for the tip, I didn't know you could do that. I ended up
> filtering the values the bulky way, 

What is "the bulky way"?

> but it gives me total control over
> what internet users feed my program.

Why does this not fill me with confidence?

As Jon Clements has already spotted a major bug in the above: using bool 
as shown is not correct. Furthermore, converting '' into 
a string does nothing, since it is already a string.

Gnarlodious, it is good that you are concerned about code injection 
attacks, but defending against them is not simple or easy. I don't intend 
to sound condescending, but when your response to being shown a simple 
filter that maps keys to types is to say "I didn't know you could do 
that", that's a good warning that your Python experience may not be quite 
up to the job of out-guessing the sort of obscure tricks hostile 
attackers may use.

If you think that defending against malicious code is simple, you should 
read this blob post:

http://tav.espians.com/a-challenge-to-break-python-security.html

and the thread which inspired it:

http://mail.python.org/pipermail/python-dev/2009-February/086401.html


How do you sanitize user input?


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


type vs. module (part2)

2011-10-17 Thread Shane
In the following t,t1 are the result of built-in call type() -- the
form that takes three arguments.
Therefore they are classes. Consider the following output:

print type(t)
>
print id(t)
>1234567
print t.__module__
>a.b.t.d

print type(t1)
>
print id(t1)
>1234568
print t1.__module__
>a.b.t.d

I now have two questions: How does Python allow two classes of the
same
type as evidenced by identical ``print type()' output and
different id
outputs?

Also, which module is t,t1 actually in? Is it "a.b.f"? Or is it
"a.b.t.d".

I am totally confused.



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


Re: Loop through a dict changing keys

2011-10-17 Thread PoD
On Sun, 16 Oct 2011 00:18:40 -0700, Jon Clements wrote:

> On Oct 16, 12:53 am, PoD  wrote:
>> On Sat, 15 Oct 2011 11:00:17 -0700, Gnarlodious wrote:
>> > What is the best way (Python 3) to loop through dict keys, examine
>> > the string, change them if needed, and save the changes to the same
>> > dict?
>>
>> > So for input like this:
>> > {'Mobile': 'string', 'context': '', 'order': '7',
>> > 'time': 'True'}
>>
>> > I want to booleanize 'True', turn '7' into an integer, escape
>> > '', and ignore 'string'.
>>
>> > Any elegant Python way to do this?
>>
>> > -- Gnarlie
>>
>> How about
>>
>> data = {
>>     'Mobile': 'string',
>>     'context': '',
>>     'order': '7',
>>     'time': 'True'}
>> types={'Mobile':str,'context':str,'order':int,'time':bool}
>>
>> for k,v in data.items():
>>     data[k] = types[k](v)
> 
> Bit of nit-picking, but:
> 
 bool('True')
> True
 bool('False')
> True
 bool('')
> False

Oops :) Brain fade.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Equal sets with unequal print and str() representations

2011-10-17 Thread Ben Finney
Ganesh Gopalakrishnan  writes:

> This probably is known, but a potential pitfall (was, for me) nevertheless.
> I suspect it is due to hash collisions between 's3' and 's13' in this
> case?

What is the actual problem? What behaviour is occurring that doesn't
match your expectation?

> >>> S1==S2
> S1==S2
> True
> >>> str(S1)
> str(S1)
> "{'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'}"
> >>> str(S2)
> str(S2)
> "{'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'}"
> >>> str(S1) == str(S2)
> False

Right, that's all correct (though I don't know why some of your
expressions are being shown twice). A deliberate property of a set is
that its items are unordered.
http://docs.python.org/library/stdtypes.html#set>

Since sets are unordered, the string representation may show the items
in an arbitrary and unpredictable sequence. Don't write any code that
depends on a predictable sequence of retrieval from an unordered
collection.

So what did you expect instead, and what supports that expectation?

-- 
 \ “When we pray to God we must be seeking nothing — nothing.” |
  `\  —Saint Francis of Assisi |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Loop through a dict changing keys

2011-10-17 Thread Gnarlodious
On Oct 16, 5:25 pm, Steven D'Aprano  wrote:

> How do you sanitize user input?
Thanks for your concern. This is what I now have, which merely expands
each value into its usable type (unquotes them):

# filter each value
try:
   var=int(var)
except ValueError:
   if var in ('False', 'True'):
  var=eval(var) # extract booleans
   else:
  var=cgi.escape(var)

This is really no filtering at all, since all CGI variables are
written to a dictionary without checking. However, if there is no
receiver for the value I should be safe, right?

I am also trapping some input at mod_wsgi, like php query strings. And
that IP address gets quarantined. If you can suggest what attack words
to block I'll thank you for it.

I also have a system to reject variables that are not in a list, but
waiting to see what the logfiles show before deploying it.

-- Gnarlie
http://Gnarlodious.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Problem with a wx notebook

2011-10-17 Thread faucheuse
Hi there,

I've created a wx NoteBook in wich I set multiples panels in wich I
set one or more sizers. But nothing displays in the notebook,
everything is outside. I've been searching an answer for 2 days ><.
Can you help me plz ? Here is my code(with only one panel, to sum up
the code) :

class StreamingActivationDialog(wx.Dialog):
def __init__(self, *args, **kwds):
# begin wxGlade: StreamingActivationDialog.__init__
kwds["style"] = wx.DEFAULT_DIALOG_STYLE
wx.Dialog.__init__(self, *args, **kwds)
self.bitmap_1_copy = wx.StaticBitmap(self, -1, wx.Bitmap("img\
\logo.png", wx.BITMAP_TYPE_ANY))
self.labelDnD = wx.StaticText(self, -1, "Si vous avez déjà un
fichier d'activation, faite le glisser dans cette fenetre")
self.keyBitmap = wx.StaticBitmap(self, -1, wx.Bitmap("img\
\key.bmp", wx.BITMAP_TYPE_ANY))
self.conclude = wx.StaticText(self, -1, _("test"),
style=wx.ALIGN_CENTRE)

### Panel ###
self.intro3_label = wx.StaticText(self, -1, "Envoyez un mail à
\nactivat...@monmail.com\ncontenant le code :",style=wx.ALIGN_CENTRE)
self.activationCode_label= wx.StaticText(self, -1,
"123456789", style=wx.TE_READONLY)
self.copy2_Button = wx.Button(self, -1, "Copier dans le presse-
papier")
self.copy2_Button.Bind(wx.EVT_BUTTON, PanelMail.onCopy)
##

self.note = wx.Notebook(self, wx.ID_ANY, style=wx.BK_LEFT,
size=wx.Size(100, 341))
self.page3 = wx.Panel(self.note)

imagelist = wx.ImageList(94, 94)
bitmap1 = wx.Bitmap("img\\a.bmp", wx.BITMAP_TYPE_BMP )
imagelist.Add(bitmap1)
self.note.AssignImageList(imagelist)

self.__set_properties()
self.__do_layout()
# end wxGlade

def __set_properties(self):
# begin wxGlade: StreamingActivationDialog.__set_properties
self.SetTitle(_("Activation de FlashProcess"))
self.SetBackgroundColour(wx.Colour(255, 255, 255))
#self.linkProblem.SetForegroundColour(wx.Colour(0, 0, 0))
# end wxGlade

def __do_layout(self):
# begin wxGlade: StreamingActivationDialog.__do_layout
self.grid_sizer_1 = wx.FlexGridSizer(6, 1, 0, 0)
self.grid_sizer_2 = wx.FlexGridSizer(1, 2, 0, 30)
self.grid_sizer_1.Add(self.bitmap_1_copy, 0, wx.TOP|wx.BOTTOM|
wx.EXPAND, 10)


### Page 3 ###
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.intro3_label, 0, wx.BOTTOM|wx.ALIGN_CENTER, 5)
sizer.Add(self.activationCode_label, 0, wx.BOTTOM|
wx.ALIGN_CENTER, 20)
sizer.Add(self.copy2_Button, 0, wx.ALIGN_CENTER, 20)

self.page3.SetSizer(sizer)
sizer.Fit(self.page3)
##

self.note.AddPage(self.page3, "", False, 0)

self.Bind(wx.EVT_TOOLBOOK_PAGE_CHANGED, self.OnPageChanged)
self.Bind(wx.EVT_TOOLBOOK_PAGE_CHANGING, self.OnPageChanging)

self.grid_sizer_1.Add(self.note, 0, wx.EXPAND, 20)
self.grid_sizer_1.Add(self.labelDnD, 0, wx.TOP|
wx.ALIGN_CENTER_HORIZONTAL, 20)
self.grid_sizer_2.Add(self.keyBitmap, 0, wx.LEFT, 10)
self.grid_sizer_2.Add(self.labelDnD, 0, wx.LEFT, 20)
self.grid_sizer_1.Add(self.grid_sizer_2, 0, wx.EXPAND, 20)
self.grid_sizer_1.Add(self.conclude, 0, wx.TOP|
wx.ALIGN_CENTER_HORIZONTAL, 20)

self.SetSizer(self.grid_sizer_1)
self.grid_sizer_1.Fit(self)
self.Layout()
# end wxGlade

def OnPageChanged(self, event):
event.Skip()

def OnPageChanging(self, event):
event.Skip()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Loop through a dict changing keys

2011-10-17 Thread Steven D'Aprano
On Sun, 16 Oct 2011 17:41:55 -0700, Gnarlodious wrote:

> On Oct 16, 5:25 pm, Steven D'Aprano  +comp.lang.pyt...@pearwood.info> wrote:
> 
>> How do you sanitize user input?
> Thanks for your concern. This is what I now have, which merely expands
> each value into its usable type (unquotes them):
> 
> # filter each value
> try:
>var=int(var)

Should be safe, although I suppose if an attacker passed (say) five 
hundred thousand "9" digits, it might take int() a while to generate the 
long int. Instant DOS attack.

A blunt object fix for that is to limit the user input to (say) 500 
characters, which should be long enough for any legitimate input string. 
But that will depend on your application.



> except ValueError:
>if var in ('False', 'True'):
>   var=eval(var) # extract booleans

Well, that's safe, but slow, and it might encourage some future 
maintainer to use eval in less safe ways. I'd prefer:

try:
{'True': True, 'False': False}[var]
except KeyError:
pass # try something else


(To be a little more user-friendly, use var.strip().title() instead of 
just var.)



>else:
>   var=cgi.escape(var)
> 
> This is really no filtering at all, since all CGI variables are written
> to a dictionary without checking. However, if there is no receiver for
> the value I should be safe, right?

What do you mean "no receiver"?

If you mean that you don't pass the values to eval, exec, use them in SQL 
queries, call external shell scripts, etc., then that seems safe to me. 
But I'm hardly an expert on security, so don't take my word on it. And it 
depends on what you end up doing in the CGI script.


> I am also trapping some input at mod_wsgi, like php query strings. And
> that IP address gets quarantined. If you can suggest what attack words
> to block I'll thank you for it.

That's the wrong approach. Don't block words in a blacklist. Block 
everything that doesn't appear in a whitelist. Otherwise you're 
vulnerable to a blackhat coming up with an attack word that you never 
thought of. There's one of you and twenty million of them. Guess who has 
the advantage?



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


define module in non-standard location?

2011-10-17 Thread Shane
Normally if one has a code set under a directory "top_level" like
this:

top_level:
   __main__.py
   a
  __init__.py
  b
 __init__.py

then this directory structure is naturally satisfies this line in
__main__.py:

>import a.b

But support, for some stupid reason --- say a.b is user defined code
--- that I want
to locate modules a and a.b somewhere else under another directory
"other_top_level".
What would the line "import a.b" in __main__,py be replaced by?

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


Re: type vs. module (part2)

2011-10-17 Thread alex23
On Oct 17, 9:11 am, Shane  wrote:
> I now have two questions: How does Python allow two classes of the
> same
> type as evidenced by identical ``print type()' output and
> different id
> outputs?

You are looking at the id of two _instances_ of the class, not of the
class itself.

>>> class Example(object):
...   pass
...
>>> e1, e2 = Example(), Example()
>>> type(e1), type(e2)
(, )
>>> id(type(e1)), id(type(e2))
(20882000, 20882000)
>>> id(e1), id(e2)
(25931760, 25968816)

> Also, which module is t,t1 actually in? Is it "a.b.f"? Or is it
> "a.b.t.d".

Which module did you declare them in? What makes you think they're
defined somewhere other than what .__module__ is telling you?

My guess is your class is in a.b.f, your instances are created in
a.b.t.d, and you've demonstrated very powerfully the value of
meaningful names in code.

> I am totally confused.

And you have the source code. Imagine how we feel.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: type vs. module (part2)

2011-10-17 Thread Steven D'Aprano
On Sun, 16 Oct 2011 16:11:18 -0700, Shane wrote:

> In the following t,t1 are the result of built-in call type() -- the form
> that takes three arguments.

Are you sure about that? Because my explanation below will depend 
entirely on this alleged fact: that t and t1 themselves are classes, not 
instances.

To be sure (well, *nearly* sure), please print t and t1 and see whether 
you get something like:

print t
=> 

or 

print t
=> 



> Therefore they are classes. Consider the following output:
> 
> print type(t)
>>
> print id(t)
>>1234567
> print t.__module__
>>a.b.t.d
> 
> print type(t1)
>>
> print id(t1)
>>1234568
> print t1.__module__
>>a.b.t.d
> 
> I now have two questions: How does Python allow two classes of the same
> type as evidenced by identical ``print type()' output and
> different id outputs?

When you use the class statement, you end up with one class with one 
name, but that's not a hard rule about classes. It's just a convention.


You can have multiple identical classes so long as you assign them to 
different names. For example:

>>> class Spam:  # bind a class "Spam" to the global name "Spam"
... pass
...
>>> Ham = Spam  # bind the class object to another global name
>>>
>>> class Spam:  # and re-use the old name for a new class
... x = 1
...
>>> print Ham, Spam
__main__.Spam __main__.Spam


What's going on here? The secret is that classes (and functions!) 
generally have *two* names. The first name is their internal name, the 
name they report when you print them. The second is the name of the 
variable (or variables!) they are bound to. Nobody says that they MUST 
match, although they often do.


When you use the class statement, Python's interpreter ensures that you 
start off with the two names matching, but as you can see from above, 
they don't necessarily stay matching. But the type() function doesn't 
enforce that:

>>> brie = type('cheese', (), {})
>>> cheddar = type('cheese', (), {})
>>> brie is cheddar
False
>>> print brie, cheddar
 

Both brie and cheddar know their own name as "cheese", but the names you 
use to refer to them are different.



So, bringing this back to your examples... 

Both t and t1 are classes, both know their internal name as "F", but they 
are different classes, as seen by the fact that their IDs are different.


> Also, which module is t,t1 actually in? Is it "a.b.f"? Or is it
> "a.b.t.d".

Since they are two independent classes, it could easily be "both, one for 
each".



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


Re: define module in non-standard location?

2011-10-17 Thread Steven D'Aprano
On Sun, 16 Oct 2011 19:43:20 -0700, Shane wrote:

> Normally if one has a code set under a directory "top_level" like this:
> 
> top_level:
>__main__.py
>a
>   __init__.py
>   b
>  __init__.py
> 
> then this directory structure is naturally satisfies this line in
> __main__.py:
> 
>>import a.b
> 
> But support, for some stupid reason --- say a.b is user defined code ---
> that I want
> to locate modules a and a.b somewhere else under another directory
> "other_top_level".

You mean like this?

top_level/
__main__.py
other_top_level/
a/
__init__.py
b/
__init__.py




> What would the line "import a.b" in __main__,py be replaced by?


Make sure other_top_level is in your PYTHONPATH, and then just use 
"import a.b" as before.


Either use your shell to do something like this:

export PYTHONPATH=other_top_level:$PYTHONPATH

(that's using bash syntax, other shells may need something different), or 
in __main__.py do this:

import sys
sys.path.append(other_top_level)



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


Re: type vs. module (part2)

2011-10-17 Thread Steven D'Aprano
On Mon, 17 Oct 2011 06:32:00 +, Steven D'Aprano wrote:

> So, bringing this back to your examples...
> 
> Both t and t1 are classes, both know their internal name as "F", but
> they are different classes, as seen by the fact that their IDs are
> different.

Oops, no, sorry, a mistake... assuming you are correct that both t and t1 
are classes, we don't have enough information to know what they believe 
they are called. (Printing t and t1 should tell you.) What we know is 
that their *metaclass* (the class of a class) knows itself as "F".


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


Re: define module in non-standard location?

2011-10-17 Thread Shane
On Oct 16, 11:55 pm, Steven D'Aprano  wrote:
> On Sun, 16 Oct 2011 19:43:20 -0700, Shane wrote:
> > Normally if one has a code set under a directory "top_level" like this:
>
> > top_level:
> >    __main__.py
> >    a
> >       __init__.py
> >       b
> >          __init__.py
>
> > then this directory structure is naturally satisfies this line in
> > __main__.py:
>
> >>import a.b
>
> > But support, for some stupid reason --- say a.b is user defined code ---
> > that I want
> > to locate modules a and a.b somewhere else under another directory
> > "other_top_level".
>
> You mean like this?
>
> top_level/
>     __main__.py
> other_top_level/
>     a/
>         __init__.py
>         b/
>             __init__.py
>
> > What would the line "import a.b" in __main__,py be replaced by?
>
> Make sure other_top_level is in your PYTHONPATH, and then just use
> "import a.b" as before.
>
> Either use your shell to do something like this:
>
> export PYTHONPATH=other_top_level:$PYTHONPATH
>
> (that's using bash syntax, other shells may need something different), or
> in __main__.py do this:
>
> import sys
> sys.path.append(other_top_level)
>
> --
> Steven

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


Re: Benefit and belief

2011-10-17 Thread DevPlayer
> DevPlayer  wrote:
> >I still assert that contradiction is caused by narrow perspective.
> >By that I mean: just because an objects scope may not see a certain
> >condition, doesn't mean that condition is non-existant.

> Groetjes Albert wrote:
> This is a far cry from the bible stating that someone is his
> own grand father. Or going to great length to prove that Jezus
> (through Jozef) is a descendant of David. Then declaring it
> a dogma that Jozef has nothing to do with it.

Do you not see? For ...
One man's garbage is another man's treasure.
One man's delusion is another man's epiphany.
One man's untruth is another man's belief.
One man's thing to attack is another mans thing to shield and defend.
One man's logical undenighable truth is another man's small part of a
bigger picture.

As has been said for example does 1+1 = 2. Only in one small
persepective. Whaa? what wack job says stuff like that?
1+1 = 10. In the bigger picture there is more then one numberic base
besides decimal, such as binary. Or then one might say there are only
10 integer numbers from 0 to 9 or from 1 to 10 if you like. Again in
the limited view, true, but in the larger view no. The Elucid
numbering scale is not the only numbering scale ever invented, or
needed for that matter.

http://en.wikipedia.org/wiki/Euclidean_geometry
"Euclid's axioms seemed so intuitively obvious that any theorem proved
from them was deemed true in an absolute, often metaphysical, sense.
Today, however, many other self-consistent non-Euclidean geometries
are known, the first ones having been discovered in the early 19th
century. An implication of Einstein's theory of general relativity is
that Euclidean space is a good approximation to the properties of
physical space ..."



> Groetjes Albert wrote:
> (It being ... well ... you know ...)
Um... Huh? sorry didn't know what you meant. You got me on that one.
Ellipses just put my brain into recursive mode.


> Groetjes Albert wrote:
> (I have this book, it is called "the amusing bible" with all
> flippant and contradictory stuff pointed out by a French
> 1930 communist. Cartoons too. )
I likely would find it very funny.


> Economic growth -- being exponential -- ultimately falters.
How true indeed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Language Enhancement Idea to help with multi-processing (your opinions please)

2011-10-17 Thread John Ladasky
On Oct 14, 7:32 pm, alex23  wrote:

> You can do this right now with Python 3.2+ and concurrent.futures:
>
> from concurrent.futures import ThreadPoolExecutor

You may have finally sold me on struggling through the upgrade from
Python 2.6!  I've been doing reasonably well with the Multiprocessing
module, but it looks like the syntax of ThreadPoolExecutor offers some
significant improvements.

Here's hoping that numpy, scipy, and matplotlib are all Python 3.x-
compatible by now...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: callling python function in c

2011-10-17 Thread Ulrich Eckhardt

Am 16.10.2011 10:03, schrieb masood shaik:

I am trying to call python function from c code.The following
program i got from the web source while i am trying to run this
program it throws an segmentation fault.


Try checking what functions returns instead of blindly using it.
Use a debugger to find out where exactly it segfaults.

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


[OT] Re: Benefit and belief

2011-10-17 Thread Steven D'Aprano
On Mon, 17 Oct 2011 05:59:04 -0700, DevPlayer wrote:

> As has been said for example does 1+1 = 2. Only in one small
> persepective. Whaa? what wack job says stuff like that? 1+1 = 10. In the
> bigger picture there is more then one numberic base besides decimal,
> such as binary.

That is no more deep and meaningful than the fact that while some people 
say "one plus one equals two", others say "eins und eins gleich zwei", 
some say "un et un fait deux" and some say "один и один дает два". 
Regardless of whether you write two, zwei, два, δυο, 2 (in decimal), 10 
(in binary), II (in Roman numerals) or even {0,1} using set theory 
notation, the number remains the same, only the symbol we use to label it 
is different.

Do not confuse the map for the territory.


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


Re: Benefit and belief

2011-10-17 Thread DevPlayer
On Oct 17, 10:34 am, Steven D'Aprano  wrote:
> On Mon, 17 Oct 2011 05:59:04 -0700, DevPlayer wrote:
> > As has been said for example does 1+1 = 2. Only in one small
> > persepective. Whaa? what wack job says stuff like that? 1+1 = 10. In the
> > bigger picture there is more then one numberic base besides decimal,
> > such as binary.
>
> That is no more deep and meaningful than the fact that while some people
> say "one plus one equals two", others say "eins und eins gleich zwei",
> some say "un et un fait deux" and some say "один и один дает два".
> Regardless of whether you write two, zwei, два, δυο, 2 (in decimal), 10
> (in binary), II (in Roman numerals) or even {0,1} using set theory
> notation, the number remains the same, only the symbol we use to label it
> is different.
>
> Do not confuse the map for the territory.
> Steven
Good point. But I disagree:

The symbol is not only used to label it. The symbol is used to put it
in context in reference to something else. "2" is a quantity in
decimal, but in binary, "2" is not a quantity nor is 01+01==10 equal
to "2" from withIN the binary perspective. Those symantics are
symbolic of concepts which are being equated to quantities OUTSIDE of
the binary perspective. True binary states, True + True does not equal
two True, correct?

Programmers use binary "math" to -represent- quantity. Here you are
arranging syntax to change meaning -out of scope-. The original
machine language notation inventors could have said in binary there is
no 1+1  they could have said "1 Jumps 1 means "A"", or "On repowers On
equals 5th gate in nand circuit".

To reitterate, I agree with you that it doesn't matter what symbology
you use if that symobology represents "same-stateness" -FROM a broader
perspective (i.e. scope). BUT in binary, in the narrow scope of binary
logic there is no "2". The available states are restrained to the
scope you place them, when WITHIN that scope. (using caps to try to be
clear and I don't intend to say you are wrong and I am right but to
say, I disagree because of this logic. Said differently I intend to
explain, not to demoralize or offend).

"1+1=10" is being viewed as 2 because of a larger world view is being
used, a broader perspective. Using broader concepts of numbers and
math which is a superset of a strictly binary system and is also a
superset of a decimal only view. Remember a computer does not function
with concepts of "2" or "a" or "15". Computers function in ons and
offs and "indeterminate" states. The binary representation of "10" to
a computer does not mean "2". That quantity representation is
something the human applies to that state.

Perhaps a differant analogy made by someone else. Many years ago, I've
studied the "The Fourth Dimension" a book based mostly on math by
Rudy Rucker. There are a few books with that name but this one is
algra based. It attempts to teach the reader to be able to view 4
dimensional objects using 3 dimensional and even 2 dimensional
translations of "mapped" objects - with a 4 dimensional view.

There are two popular schools of thought on this attempt. 1. It's
impossible or us to concieve of a 4 dimentional space objects within
our 3 dimentional senses and perceptions. and 2. We can conceive  with
our mind-s eye 4 dimensional objects much like we concieve of 2
dimentional objects (the plane) and even harder one dimensional
objects.

The author attempts to teach by first using an analogy. First he
clarifies that for his purposes of 4 dimensional space, that no
dimension axis in his math singularly represents time or anything
ephemeral like the supernatural or energy or such. Each fo the 4
dimensions represent an axis in a physical vector. He then creates a 3
dimensional man who lives in a 3 dimensional world. This 3d man sees
up, down, north, south, east, west. And he can see a plane or even a
line. But the 3d man does not see the 4th axis because he is not made
of that vector and does not therefore have sensory to perceive that
axis.  The author then goes on to show a 2d man does not see the 3rd
axis and then better explains how the 1d man can only "see" in left or
right directions. Following that story further, keeping to certain
assumptions about 1d space, puts the man in a binary world view, where
there is no "2", much like a computer. there is not "2" there is only
10, which TO YOU is a 2. but to the 1d man and the computer is a 10.

Of course when you try to limit someone's view to make a point about a
limited view it sounds rediculas. Supposition is often that way after
all.

> That is no more deep and meaningful than the fact that while some people
> say "one plus one equals two", others say "eins und eins gleich zwei",
> some say "un et un fait deux" and some say "один и один дает два".
> Regardless of whether you write two, zwei, два, δυο, 2 (in decimal), 10
> (in binary), II (in Roman numerals) or even {0,1} using set theory
> notation, the number remains the same, only the symbol we use to label it

Re: Loop through a dict changing keys

2011-10-17 Thread Gnarlodious
Steven: Thanks for those tips, I've implemented all of them. Also only
allowing whitelisted variable names. Feeling much more confident.

-- Gnarlie

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


Re: Python hangs: Problem with wxPython, threading, pySerial, or events?

2011-10-17 Thread Ethan Swint
I just wanted to bump this back onto the list since I posted over the 
weekend.


Thanks,
Ethan

On 10/15/2011 11:17 AM, Ethan Swint wrote:

Hi-

I'm experiencing crashes in my Win32 Python 2.7 application which 
appear to be linked to pyzmq.  At the moment, I can't even kill the 
"python.exe *32" process in the Windows Task Manager.  I'm running the 
script using Ipython by calling


C:\Python27\pythonw.exe 
"/python27/scripts/ipython-qtconsole-script.pyw" -pylab


but I also experience similar behavior when running within Eclipse.  
I've included an error message at the end which appears in the Windows 
'cmd' window, but the message is not reflected in the pylab window.


My attached device is transmitting <160><1><2><3><4><80> and is 
received correctly when I run the sample pyserial script 
'wxTerminal.py'.  In my application, however, the message appears to 
get characters out of order or drop bytes.


If there's a better place to post or if you'd like more info, let me 
know.


Thanks,
Ethan

--Serial Port Listening 
Thread

def MotorRxThread(self):
"""Thread that handles the incoming traffic. Does buffer input and 
generates an SerialRxEvent"""
while self.alive.isSet():   #loop while alive event is 
true

  text = self.serMotor.read(1)  #read one, with timeout
  if text:#check if not timeout
n = self.serMotor.inWaiting() #look if there is more to read
if n:
  text = text + self.serMotor.read(n) #get it
#log to terminal
printstring = "MotorRxThread: "
for b in text:
  printstring += str(ord(b)) + " "
print printstring
#pdb.set_trace()
if self.motorRx0.proc_string(text):
  print "Message: cmd: " + str(self.motorRx0.cmd) + " data: " 
+ str(self.motorRx0.data)

  event = SerialRxSpeedEvent(self.GetId(), text)
  self.GetEventHandler().AddPendingEvent(event)
-\Serial Port Listening 
Thread


Thread 
Start&Stop--

  def StartMotorThread(self):
"""Start the receiver thread"""
self.motorThread = threading.Thread(target=self.MotorRxThread)
self.motorThread.setDaemon(1)
self.alive.set()
self.motorThread.start()

  def StopMotorThread(self):
"""Stop the receiver thread, wait until it's finished."""
if self.motorThread is not None:
self.alive.clear()  #clear alive event for thread
self.motorThread.join()  #wait until thread has finished
self.motorThread = None
self.serMotor.close()  #close the serial port connection
\Thread 
Start&Stop--


---Error message 


ValueError: '' is not in list
([], ['', '', '', 
'{"date":"2011-10-15T10:24:27.231000","username":"kernel","session":"82906c8a-1235-44d0-b65d-
0882955305c1","msg_id":"7cfcd155-bc05-4f47-9c39-094252223dab","msg_type":"stream"}', 
'{"date":"2011-10-15T10:24:27.23100
0","username":"kernel","session":"82906c8a-1235-44d0-b65d-0882955305c1","msg_id":"f4b88228-b353-4cfb-9bbe-ae524ee1ac38", 

"msg_type":"stream"}', 
'{"date":"2011-10-15T10:24:00.774000","username":"username","session":"9f393860-c2ab-44e9-820d-8f
08ae35044e","msg_id":"13a46e93-8da2-487b-ab12-6cae47b1ac34","msg_type":"execute_request"}', 
'{"date":"2011-10-15T10:24:0
0.774000","username":"username","session":"9f393860-c2ab-44e9-820d-8f08ae35044e","msg_id":"13a46e93-8da2-487b-ab12-6cae4 

7b1ac34","msg_type":"execute_request"}', '{"data":"\\nMotorRxThread: 0 
MotorRxThread: 4 ","name":"stdout"}'])
ERROR:root:Exception in I/O handler for fd object at 0x03ADFCC0>

Traceback (most recent call last):
  File 
"C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\ioloop.py", 
line 291, in start

self._handlers[fd](fd, events)
  File 
"C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\stack_context.py", 
line 133, in wrapped

callback(*args, **kwargs)
  File "C:\Python27\lib\site-packages\IPython\zmq\kernelmanager.py", 
line 448, in _handle_events

self._handle_recv()
  File "C:\Python27\lib\site-packages\IPython\zmq\kernelmanager.py", 
line 458, in _handle_recv

ident,msg = self.session.recv(self.socket)
  File "C:\Python27\lib\site-packages\IPython\zmq\session.py", line 
585, in recv

raise e
ValueError: No JSON object could be decoded
ERROR:root:Exception in I/O handler for fd object at 0x03ADFCC0>

Traceback (most recent call last):
  File 
"C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\ioloop.py", 
line 291, in start

self._handlers[fd](fd, events)
  File 
"C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\stack_context.py", 
line 133,

Re: How to test if object is an integer?

2011-10-17 Thread Mathias Lafeldt
On Sat, Oct 15, 2011 at 1:44 AM, MrPink  wrote:
>
> Is there a function in Python that can be used to test if the value in
> a string is an integer?  I had to make one up for myself and it looks
> like this:
>
> def isInt(s):
>    try:
>        i = int(s)
>        return True
>    except ValueError:
>        return False

According to [1], there're more Exceptions to test for:

try:
int(s)
return True
except (TypeError, ValueError, OverflowError): # int conversion failed
return False

[1] http://jaynes.colorado.edu/PythonIdioms.html, idiom "Catch errors
rather than avoiding them to avoid cluttering your code with special
cases"

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


Re: Equal sets with unequal print and str() representations

2011-10-17 Thread Ganesh Gopalakrishnan
Thanks to all who replied - also to Ben. I had foolishly assumed that 
the same set exhibits the same rep on at least one platform. Like any 
bug, the falsity of my assumption took months to expose - till then, 
things had worked fine. Needless to say I'm new to Python.  (The double 
printing is because I tend to work within an Emacs inferior shell.)


Cheers,

Ganesh

On 10/16/11 8:23 PM, Ben Finney wrote:

Ganesh Gopalakrishnan  writes:


This probably is known, but a potential pitfall (was, for me) nevertheless.
I suspect it is due to hash collisions between 's3' and 's13' in this
case?

What is the actual problem? What behaviour is occurring that doesn't
match your expectation?


S1==S2

S1==S2
True

str(S1)

str(S1)
"{'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'}"

str(S2)

str(S2)
"{'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'}"

str(S1) == str(S2)

False

Right, that's all correct (though I don't know why some of your
expressions are being shown twice). A deliberate property of a set is
that its items are unordered.
 http://docs.python.org/library/stdtypes.html#set>

Since sets are unordered, the string representation may show the items
in an arbitrary and unpredictable sequence. Don't write any code that
depends on a predictable sequence of retrieval from an unordered
collection.

So what did you expect instead, and what supports that expectation?


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


Re: How to test if object is an integer?

2011-10-17 Thread Noah Hall
On Sat, Oct 15, 2011 at 12:44 AM, MrPink  wrote:
>
> Is there a function in Python that can be used to test if the value in
> a string is an integer?  I had to make one up for myself and it looks
> like this:
>
> def isInt(s):
>    try:
>        i = int(s)
>        return True
>    except ValueError:
>        return False


There's the isdigit method, for example -

>>> str = "1324325"
>>> str.isdigit()
True
>>> str = "1232.34"
>>> str.isdigit()
False
>>> str = "I am a string, not an int!"
>>> str.isdigit()
False
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Benefit and belief

2011-10-17 Thread Ben Finney
DevPlayer  writes:

> Do you not see? For ...
> One man's delusion is another man's epiphany.
> One man's untruth is another man's belief.
> One man's logical undenighable truth is another man's small part of a
> bigger picture.

Those are just not true.

A belief that doesn't match reality is a delusion. That doesn't change
when someone thinks it's an epiphany: it's still a delusion.

If a claim about reality doesn't actually match reality, it's untrue.
That doesn't change when someone believes it: it's still untrue, or
claims it's “part of a bigger picture”.

If you make claims about reality, then you'd better be ready for them to
be subjected to the tests of reality, or be ready for ridicule if you
can't back them up with such tests.

If, on the other hand, you claim a “bigger picture”, then that's just
another scope within reality and you haven't escaped any part of your
burden to demonstrate that reality.

If, on the gripping hand, you want to make claims that are *not* about
reality, then be very clear about that at the beginning and don't try to
shift the goalposts later.

> http://en.wikipedia.org/wiki/Euclidean_geometry
> "Euclid's axioms seemed so intuitively obvious that any theorem proved
> from them was deemed true in an absolute, often metaphysical, sense.
> Today, however, many other self-consistent non-Euclidean geometries
> are known, the first ones having been discovered in the early 19th
> century. An implication of Einstein's theory of general relativity is
> that Euclidean space is a good approximation to the properties of
> physical space ..."

Yes. Anyone who claimed that Euclids axioms hold in real spacetime was
*wrong*. If they believed it, they were *deluded*.

There was no shame in that before the discovery that Euclid's axioms
don't hold in real spacetime. But, once its falseness has been
demonstrated, to handwave about “one man's truth” and “bigger picture”
is an attempt to avoid the admission that the claim was false.

It is uncomfortable – sometimes painful – to admit that one's belief
does not match reality; and hence natural and common for us to seek to
avoid that admission when the evidence is against our belief. But that
doesn't lessen the delusion.

-- 
 \“Human reason is snatching everything to itself, leaving |
  `\   nothing for faith.” —Bernard of Clairvaux, 1090–1153 CE |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Equal sets with unequal print and str() representations

2011-10-17 Thread Ben Finney
Ganesh Gopalakrishnan  writes:

> Thanks to all who replied - also to Ben.

You're welcome. (Please don't top-post your replies.)

> Needless to say I'm new to Python.

Welcome to this forum, then! You would be wise to get a solid grounding
in Python by working through the Python tutorial from beginning to end
http://docs.python.org/tutorial/>. Perform each exercise,
experiment with it until you understand, and only then move on to the
next. Repeat until done :-)

-- 
 \   “Know what I hate most? Rhetorical questions.” —Henry N. Camp |
  `\   |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if object is an integer?

2011-10-17 Thread Ian Kelly
On Mon, Oct 17, 2011 at 2:44 PM, Noah Hall  wrote:
> There's the isdigit method, for example -
>
 str = "1324325"
 str.isdigit()
> True
 str = "1232.34"
 str.isdigit()
> False
 str = "I am a string, not an int!"
 str.isdigit()
> False

That works for non-negative base-10 integers.  But:

>>> "-1234".isdigit()
False

Cheers,
Ian
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if object is an integer?

2011-10-17 Thread Roy Smith
In article ,
 Mathias Lafeldt  wrote:

> According to [1], there're more Exceptions to test for:
> 
> try:
> int(s)
> return True
> except (TypeError, ValueError, OverflowError): # int conversion failed
> return False


I don't think I would catch TypeError here.  It kind of depends on how 
isInt() is defined.  Is it:

def isInt(s):
  "Return True if s is a string representing an integer"

or is it:

def isInt(s):
  "Return True if s (which must be a string) represents an integer"

If the latter, then passing a non-string violates the contract, and the 
function should raise TypeError.  If the former, then you could make 
some argument for catching the TypeError and returning False, but I 
think the second version is what most people have in mind for isInt().

Can you even get an OverflowError any more in a modern Python?

>>> 
int('9')
9L
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if object is an integer?

2011-10-17 Thread Chris Kaynor
Python 2.6 running on Windows 7:
>>> 99.0**99**99
OverflowError: (34, 'Result too large')
Traceback (most recent call last):
  File "", line 1, in 
OverflowError: (34, 'Result too large')

However, from the documentation:
"Because of the lack of standardization of floating point exception
handling in C, most floating point operations also aren’t checked."
(http://docs.python.org/library/exceptions.html#exceptions.OverflowError)

Chris

On Mon, Oct 17, 2011 at 5:33 PM, Roy Smith  wrote:
>
> In article ,
>  Mathias Lafeldt  wrote:
>
> > According to [1], there're more Exceptions to test for:
> >
> > try:
> >     int(s)
> >     return True
> > except (TypeError, ValueError, OverflowError): # int conversion failed
> >     return False
>
>
> I don't think I would catch TypeError here.  It kind of depends on how
> isInt() is defined.  Is it:
>
> def isInt(s):
>  "Return True if s is a string representing an integer"
>
> or is it:
>
> def isInt(s):
>  "Return True if s (which must be a string) represents an integer"
>
> If the latter, then passing a non-string violates the contract, and the
> function should raise TypeError.  If the former, then you could make
> some argument for catching the TypeError and returning False, but I
> think the second version is what most people have in mind for isInt().
>
> Can you even get an OverflowError any more in a modern Python?
>
> >>>
> int('9')
> 9L
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if object is an integer?

2011-10-17 Thread Ian Kelly
On Mon, Oct 17, 2011 at 6:40 PM, Chris Kaynor  wrote:
> Python 2.6 running on Windows 7:
 99.0**99**99
> OverflowError: (34, 'Result too large')
> Traceback (most recent call last):
>   File "", line 1, in 
> OverflowError: (34, 'Result too large')
>
> However, from the documentation:
> "Because of the lack of standardization of floating point exception
> handling in C, most floating point operations also aren’t checked."
> (http://docs.python.org/library/exceptions.html#exceptions.OverflowError)

I think what Roy meant was "can you even get an OverflowError from
calling int() any more", to which I think the answer is no, since in
modern Pythons int() will auto-promote to a long, and in Python 3
they're even the same thing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if object is an integer?

2011-10-17 Thread Yingjie Lan




- Original Message -
> From: Noah Hall 
> To: MrPink 
> Cc: python-list@python.org
> Sent: Tuesday, October 18, 2011 4:44 AM
> Subject: Re: How to test if object is an integer?

> There's the isdigit method, for example -
> 
  str = "1324325"
  str.isdigit()
> True
  str = "1232.34"
  str.isdigit()
> False
  str = "I am a string, not an int!"
  str.isdigit()
> False
>

There are some corner cases to be considered with this approach:
1. negative integers: '-3'
2. strings starting with '0': '03'
3. strings starting with one '+': '+3'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if object is an integer?

2011-10-17 Thread Steven D'Aprano
On Mon, 17 Oct 2011 18:59:44 -0600, Ian Kelly wrote:

> On Mon, Oct 17, 2011 at 6:40 PM, Chris Kaynor 
> wrote:
>> Python 2.6 running on Windows 7:
> 99.0**99**99
>> OverflowError: (34, 'Result too large') Traceback (most recent call
>> last):
>>   File "", line 1, in 
>> OverflowError: (34, 'Result too large')
>>
>> However, from the documentation:
>> "Because of the lack of standardization of floating point exception
>> handling in C, most floating point operations also aren’t checked."
>> (http://docs.python.org/library/
exceptions.html#exceptions.OverflowError)
> 
> I think what Roy meant was "can you even get an OverflowError from
> calling int() any more", to which I think the answer is no, since in
> modern Pythons int() will auto-promote to a long, and in Python 3
> they're even the same thing.


You can still get an OverflowError:

>>> inf = float('inf')
>>> int(inf)
Traceback (most recent call last):
  File "", line 1, in 
OverflowError: cannot convert float infinity to integer


and similarly for Decimal('inf') as well.


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


Re: Fwd: os.statvfs bug or my incompetence ?

2011-10-17 Thread Peter G. Marczis

Hi,
not yet, I will check it today, thanks for the idea !
We may have some deeper problem...
Br,
Peter.

On 10/15/2011 05:46 PM, ext Kev Dwyer wrote:

Peter G. Marczis wrote:



Hello Peter,

Welcome to the list.

Have you tried calling statvfs from a C program?  What happens if you do?

Best regards,

Kev






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