Re: Number of distinct substrings of a string [continuation]

2009-11-29 Thread n00m
On Nov 29, 11:43 pm, Bearophile  wrote:
> Anyway, you may try a pure-Python2.x 
> implementation:http://suffixtree.googlecode.com/files/suffixtree-0.1.py

Ouch, Bearie... 214 lines of code are there.
Ok.. I tested it.
Firstly I replaced all "print " with "pass##print "
(aiming to avoid intensive printing from inside of the code).

Then I left in its final part only building of suffix trees.

==
...
...
...

from time import time
t = time()

import sys
sys.stdin = open('D:/88.txt', 'rt')
f = sys.stdin.read().split()
sys.stdin.close()

z = open('D:/99.txt', 'wt')

for tc in range(int(f[0])):
s = f[tc + 1]
test_str = s + '$'
POSITIVE_INFINITY = len(test_str) - 1
suffix_tree = SuffixTree(test_str)
print >> z, 'len(s) =', len(s)

print >> z, 'time =', time() - t
z.close()


Output:

len(s) = 1000
len(s) = 1000
len(s) = 1
time = 0.64132425


0.64s > 0.48s (of my algo)
I.e. the code can't help in my very special and narrow case.

But of course it is worthy to be studied and memoized.
E.g.:
from huge string "s" we built its Suffix Tree.
Now we are given arbitrary string "ss".
Task: to find the largest its prefix occured in "s",
traversing its Suffix Tree.




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


Re: Object Not Callable, float?

2009-11-29 Thread Ben Finney
"W. eWatson"  writes:

> I think I understand it, but how does one prevent it from happening,
> or know it's the cause? That msg I got?

Yes. The line of code was pretty clear: you were attempting to call an
object, and the error message said the object's type doesn't support
being called.

More generally, you should insert an automatic step into your workflow
where you run a static code checker like ‘pyflakes’ over all of your
code to catch common errors and mistakes.

-- 
 \“To me, boxing is like a ballet, except there's no music, no |
  `\   choreography, and the dancers hit each other.” —Jack Handey |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python logging filters

2009-11-29 Thread Grimsqueaker
On Nov 30, 8:42 am, Grimsqueaker  wrote:
> On Nov 28, 11:26 am, Vinay Sajip  wrote:
>
>
>
> > On Nov 27, 1:11 pm, Grimsqueaker  wrote:
>
> > > When I add a Filter to a Handler, everything works as expected (ie.
> > > all messages sent from Loggers below the Filter's level are allowed
> > > through), but when I add the Filter directly on to the Logger, only
> > > that Logger is blocked, regardless of the contents of the Filter.
>
> > The key thing to remember is that when a logger processes an event,
> > handlers attached to it *and all its parents* are offered the event
> > for handling. In the case where you have just one handler and it has
> > the filter attached, filtering works as you expected. By attaching the
> > filter to the root logger, you are not filtering its handler; this
> > handler is invoked for events logged to all the other loggers, and so
> > (apart from the event at the root logger) those events are not
> > filtered.
>
> > For some examples of filter usage, see this post:
>
> >http://groups.google.com/group/comp.lang.python/msg/2eb4cf8f879c6451
>
> > Regards,
>
> > Vinay Sajip
>
> OK, that makes sense, but does this mean that I am unable to block a
> logging path from one point? ie. in my example, I would have to add
> Filter(loggerB.name) to every Logger in the 'A' path to block the A
> path from showing at my root Handler? Is there no way I can just block
> the whole 'A' path from one point? I was under the impression that
> Filters worked hierarchically and that a message would be passed up
> the chain of Loggers until it was stopped by a Filter (or its loglevel
> was not allowed).
>
> Thanks for your help

So would I be correct in saying that Filters apply only the the object
they are attached to and have no effect on how messages are propagated
through the logging hierarchy? If this is the case my next question
would be: How can I affect whether or not a message is propagated
further up the tree?

Sorry to post again so quickly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python logging filters

2009-11-29 Thread Grimsqueaker
On Nov 30, 8:42 am, Grimsqueaker  wrote:
> On Nov 28, 11:26 am, Vinay Sajip  wrote:
>
>
>
> > On Nov 27, 1:11 pm, Grimsqueaker  wrote:
>
> > > When I add a Filter to a Handler, everything works as expected (ie.
> > > all messages sent from Loggers below the Filter's level are allowed
> > > through), but when I add the Filter directly on to the Logger, only
> > > that Logger is blocked, regardless of the contents of the Filter.
>
> > The key thing to remember is that when a logger processes an event,
> > handlers attached to it *and all its parents* are offered the event
> > for handling. In the case where you have just one handler and it has
> > the filter attached, filtering works as you expected. By attaching the
> > filter to the root logger, you are not filtering its handler; this
> > handler is invoked for events logged to all the other loggers, and so
> > (apart from the event at the root logger) those events are not
> > filtered.
>
> > For some examples of filter usage, see this post:
>
> >http://groups.google.com/group/comp.lang.python/msg/2eb4cf8f879c6451
>
> > Regards,
>
> > Vinay Sajip
>
> OK, that makes sense, but does this mean that I am unable to block a
> logging path from one point? ie. in my example, I would have to add
> Filter(loggerB.name) to every Logger in the 'A' path to block the A
> path from showing at my root Handler? Is there no way I can just block
> the whole 'A' path from one point? I was under the impression that
> Filters worked hierarchically and that a message would be passed up
> the chain of Loggers until it was stopped by a Filter (or its loglevel
> was not allowed).
>
> Thanks for your help

So would I be correct in saying that Filters apply only the the object
they are attached to and have no effect on how messages are propagated
through the logging hierarchy? If this is the case my next question
would be: How can I affect whether or not a message is propagated
further up the tree?

Sorry to post again so quickly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python logging filters

2009-11-29 Thread Grimsqueaker
On Nov 28, 11:26 am, Vinay Sajip  wrote:
> On Nov 27, 1:11 pm, Grimsqueaker  wrote:
>
> > When I add a Filter to a Handler, everything works as expected (ie.
> > all messages sent from Loggers below the Filter's level are allowed
> > through), but when I add the Filter directly on to the Logger, only
> > that Logger is blocked, regardless of the contents of the Filter.
>
> The key thing to remember is that when a logger processes an event,
> handlers attached to it *and all its parents* are offered the event
> for handling. In the case where you have just one handler and it has
> the filter attached, filtering works as you expected. By attaching the
> filter to the root logger, you are not filtering its handler; this
> handler is invoked for events logged to all the other loggers, and so
> (apart from the event at the root logger) those events are not
> filtered.
>
> For some examples of filter usage, see this post:
>
> http://groups.google.com/group/comp.lang.python/msg/2eb4cf8f879c6451
>
> Regards,
>
> Vinay Sajip

OK, that makes sense, but does this mean that I am unable to block a
logging path from one point? ie. in my example, I would have to add
Filter(loggerB.name) to every Logger in the 'A' path to block the A
path from showing at my root Handler? Is there no way I can just block
the whole 'A' path from one point? I was under the impression that
Filters worked hierarchically and that a message would be passed up
the chain of Loggers until it was stopped by a Filter (or its loglevel
was not allowed).

Thanks for your help
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python py2exe - memory load error

2009-11-29 Thread prakash jp
Try to install "vcredist_x86.exe", then try to build using py2exe. I think
that should solve the issue

Regards
Prakash

On Mon, Nov 30, 2009 at 10:40 AM, koranthala  wrote:

> This is cross post from stackoverflow - I couldnt get the solution
> there. Hopefully, nobody would mind.
>
> I am creating a medium level application in Python. Everything works
> well now, and I am trying to make this a windows executable with
> py2exe. The executable is created fine, but when I try to run it, it
> fails with the following error.
>
>  File "zipextimporter.pyc", line 82, in load_module
>  File "pyAA\__init__.pyc", line 1, in ?
>  File "zipextimporter.pyc", line 82, in load_module
>  File "pyAA\AA.pyc", line 8, in ?
>  File "zipextimporter.pyc", line 82, in load_module
>  File "pyAA\pyAAc.pyc", line 5, in ?
>  File "zipextimporter.pyc", line 98, in load_module
> ImportError: MemoryLoadLibrary failed loading pyAA\_pyAAc.pyd
>
> I am using pyAA in this application. I searched internet, but was
> unable to get any solution. I copied msvcp71.dll to windows/system32,
> but still issue is there.
>
> I had solved it earlier (around 7 months back), but my hard drive
> crashed and when I try to recreate it, I cannot seem to solve it
> now. :-(
>
> I would be much obliged if someone could help me out here.
>
> When I use py2exe without bundle files option, it is working
> perfectly. But when I use bundle file option, it is failing.
>
> I tried without zipfile option, wherein it creates a library.zip
> alongwith the executable. Again it failed. I did unzip of library.zip
> using 7-zip, and found that _pyAAc.pyd is there in pyAA folder inside
> the zip file. So, it looks like some issue with memoryloadlibrary
> function.
>
> >dir
> 11/30/2009  09:48 AM25,172 AA.pyc
> 11/30/2009  09:48 AM 3,351 Defer.pyc
> 11/30/2009  09:48 AM 2,311 Path.pyc
> 11/30/2009  09:48 AM11,216 pyAAc.pyc
> 11/30/2009  09:48 AM 5,920 Watcher.pyc
> 08/20/2005  02:00 PM49,152 _pyAAc.pyd
> 11/30/2009  09:48 AM   162 __init__.pyc
>
> >From the trace it does look like it can extract AA.pyc etc. I am using
> windows7 - can it be some clue?
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Object Not Callable, float?

2009-11-29 Thread Mel
W. eWatson wrote:

> I think PL/I, FORTRAN, ALGOL, etc. have reserved words.

Algol reserved syntactic tokens that resembled English words, but specified 
that they should be written in a different way from programmer-defined 
symbols, so no conflict was possible.  Published algorithms might have the 
tokens underlined or boldfaced.  In the Algol-60 I used, the tokens had to 
be enclosed in apostrophes.  None of this applied to library subroutine 
names; it was open season on those.

In FORTRAN and PL/I words were un-reserved to a degree that's really 
bizarre.  A short post can't begin to do it justice -- let's just mention 
that IF and THEN could be variable names, and DO 100 I=1.10 .  The syntaxes 
were carefully crafted so that context completely determined whether a 
symbol would be taken in a reserved sense or a programmer-defined sense, so 
any possibility for conflict was a syntax error.

Mel.


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


Re: Object Not Callable, float?

2009-11-29 Thread Lie Ryan

On 11/30/2009 4:20 PM, W. eWatson wrote:

John Bokma wrote:

"W. eWatson"  wrote:


Yikes. Thanks very much. Python seems to act unlike other language in
which words like float are reserved. I'll use asum.


The problem is that there is a function sum and you creating a float sum:

sum = 0.0

and

mean = sum(hist)

even if both could exist side by side it would be very confusing IMO.

John

I think I understand it, but how does one prevent it from happening, or
know it's the cause? That msg I got?

I think PL/I, FORTRAN, ALGOL, etc. have reserved words.


Generally, use PyLint or similar tools; they'll warn you.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Feature request: String-inferred names

2009-11-29 Thread The Music Guy
On Sun, Nov 29, 2009 at 11:01 PM, Brad Harms wrote:

>
> May the Penguin in the sky bless your every subroutine,
>

Um...feel free to ignore that.  >_>

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


Re: Exec Statement Question

2009-11-29 Thread Terry Reedy

Dave Angel wrote:

exec is a statement, and statements don't have "return values."   It's 
not a function, 


In 3.x, it is a function, though the use of print as a statement 
indicates that the OP was using 2.x.


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


Re: ANN: GMPY 1.11rc1 is available

2009-11-29 Thread Terry Reedy

casevh wrote:

Everyone,

I'm pleased to annouce that a new version of GMPY is available.
GMPY is a wrapper for the MPIR or GMP multiple-precision
arithmetic library. GMPY 1.11rc1 is available for download from:


Is this an update of the gmpy (1.02) registered at
http://pypi.python.org/pypi/gmpy/1.02?

Either way, please list it (with modified name if needed) and note that 
it is 3.x compatible so people searching for such packages can find it.


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


Re: Object Not Callable, float?

2009-11-29 Thread W. eWatson

John Bokma wrote:

"W. eWatson"  wrote:

Yikes. Thanks very much. Python seems to act unlike other language in 
which words like float are reserved. I'll use asum.


The problem is that there is a function sum and you creating a float sum:

sum = 0.0

and

mean = sum(hist)

even if both could exist side by side it would be very confusing IMO.

John
I think I understand it, but how does one prevent it from happening, or 
know it's the cause? That msg I got?


I think PL/I, FORTRAN, ALGOL, etc. have reserved words.
--
http://mail.python.org/mailman/listinfo/python-list


Re: semantics of ** (unexpected/inconsistent?)

2009-11-29 Thread inhahe
On Sun, Nov 29, 2009 at 8:04 PM, Esmail  wrote:
> Chris Rebert wrote:
> Wow .. never heard of Concatenative_languages languages before or the
> distinction you make. Your distinction explains the behavior, but I
> find it somewhat counter-intuitive. (I use the Python interpreter frequently
> for small calculations - otherwise I'd never have realized this)


Well I think of it like this
-3**2, because of the order of operations as you know, groups as -(3**2)
now if you set x to -3, (-3) is now automatically, inseparably
grouped. so in a sense by setting x to that you're grouping it.
x == (-3)
x**2 == (-3)**2

if it still seems counterintuitive, what about the fact that it's
exactly the same way in Algebra?

basic algebra:
  -3(superscript)2 is -9
  but if x is -3, then x(superscript)2 is 9
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Variables with cross-module usage

2009-11-29 Thread Lie Ryan

On 11/30/2009 12:00 PM, Terry Reedy wrote:

Dennis Lee Bieber wrote:


In these languages, the names always refer to the same location.
Python confuses matters by having names that don't really refer to
location, but are attached to the objects.


In everyday life and natural languages, names refer to people, other
objects, roles, and only occasionally to places that can be occupied. I
could claim that it is classical computer languages that confuse by
restricting names to locations in a linear sequence. You are just used
to the straightjacket ;-).


In everyday life and natural languages, though an object may have many 
names/aliases; once objects are assigned a name, it is practically 
impossible to change the name to the object the name will be practically 
stuck to it forever. In everyday life and natural languages, a single 
name can be used to refer to multiple objects just by context without 
referring any namespace. Let's not start making analogism between nature 
and silicon.


And of all, no one is confused. It is just a matter of assigning new 
shade of meaning to a word.

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


Python py2exe - memory load error

2009-11-29 Thread koranthala
This is cross post from stackoverflow - I couldnt get the solution
there. Hopefully, nobody would mind.

I am creating a medium level application in Python. Everything works
well now, and I am trying to make this a windows executable with
py2exe. The executable is created fine, but when I try to run it, it
fails with the following error.

  File "zipextimporter.pyc", line 82, in load_module
  File "pyAA\__init__.pyc", line 1, in ?
  File "zipextimporter.pyc", line 82, in load_module
  File "pyAA\AA.pyc", line 8, in ?
  File "zipextimporter.pyc", line 82, in load_module
  File "pyAA\pyAAc.pyc", line 5, in ?
  File "zipextimporter.pyc", line 98, in load_module
ImportError: MemoryLoadLibrary failed loading pyAA\_pyAAc.pyd

I am using pyAA in this application. I searched internet, but was
unable to get any solution. I copied msvcp71.dll to windows/system32,
but still issue is there.

I had solved it earlier (around 7 months back), but my hard drive
crashed and when I try to recreate it, I cannot seem to solve it
now. :-(

I would be much obliged if someone could help me out here.

When I use py2exe without bundle files option, it is working
perfectly. But when I use bundle file option, it is failing.

I tried without zipfile option, wherein it creates a library.zip
alongwith the executable. Again it failed. I did unzip of library.zip
using 7-zip, and found that _pyAAc.pyd is there in pyAA folder inside
the zip file. So, it looks like some issue with memoryloadlibrary
function.

>dir
11/30/2009  09:48 AM25,172 AA.pyc
11/30/2009  09:48 AM 3,351 Defer.pyc
11/30/2009  09:48 AM 2,311 Path.pyc
11/30/2009  09:48 AM11,216 pyAAc.pyc
11/30/2009  09:48 AM 5,920 Watcher.pyc
08/20/2005  02:00 PM49,152 _pyAAc.pyd
11/30/2009  09:48 AM   162 __init__.pyc

>From the trace it does look like it can extract AA.pyc etc. I am using
windows7 - can it be some clue?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feature request: String-inferred names

2009-11-29 Thread Brad Harms
On Sun, Nov 29, 2009 at 9:59 PM, Carl Banks wrote:

> Another thing that can be determined through common sense is that if
> you have object that you are calling getattr and setattr on so much
> that you think you need special syntax, you should have been using a
> dict.
>

(Re-send; original was sent to the wrong address. I--I mean, Gmail--sent it
to the wrong address by mistake. :P )

While you were writing this and your previous reply I was working on a
response that kind of covers what you were talking about, but I'm going to
say something anyway.

Well, yes, the names would have to be determined at run time. That's what
getattr and setattr do, except that that do it in the context of an object
rather than the local scope. However, I was under the impression that
python's mechanism for looking up local names was the same as the mechanism
used to look up attributes because names and attributes seem to function
pretty much the same way. This I assumed because of the functionality of the
locals() and globals() functions, which seem to act like the __dict__
attribute on objects except that the work on the current scope. Also, there
is the __builtins__ module, which actually _is_ an object, but its names can
be accessed in the same way as locals and globals.

I had considered the possibility of a peformance hit, however I didn't
anticipate that it would be all that much. Not that it matters, but how much
are we talking? 10% ? 50% ? In any case, I'm not really an expert on
Python's internal constructions, but because of this discussion I'm
considering taking some time to learn them.


Python is unique compared to several other languages in that it makes a
distinction between "items" and "attributes". Some languages, like
JavaScript and Lua, do not make this distinction. They leave it to the
programmer to access members of an object either as an item or as an
attribute. I don't think there is necessarily anything wrong with this, nor
do I think there is anything wrong with Python's separation.

That said, just because you can use the proposed syntax to use an object in
the same way as a dict does not mean that it works the other way around. I'm
not talking about the allowance of any specific object to have any number of
pairings between arbitrary keys and values. That's what dicts are for, and
that's what indexing syntax implies.

Rather, I'm talking about specific, concrete variables which objects are
expected (though not technically required) to have bound to them according
to how the object is intended to be used. (That's probably not the best
definition of an attribute, but it's the best I can think of ATM.)

I'm not trying to discard Python's distinction between items and attributes,
but I don't want to be limited by it due to mere syntactical constraints,
either.

May the Penguin in the sky bless your every subroutine,

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


Re: Noobie python shell question

2009-11-29 Thread Dave Angel



Tim Chase wrote:



(as an aside, is there a way to get a local/global variable from a 
string like one can fetch a variable from a class/object with 
getattr()?  Something like getattr(magic_namespace_here, "hello") used 
in the above context?  I know it can be done with eval(), but that's 
generally considered unsafe unless you vet your input thoroughly)




I think you're looking for
globals()["hello"],or of course magic_namespace=globals()

DaveA

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


Re: Object Not Callable, float?

2009-11-29 Thread John Bokma
"W. eWatson"  wrote:

> Yikes. Thanks very much. Python seems to act unlike other language in 
> which words like float are reserved. I'll use asum.

The problem is that there is a function sum and you creating a float sum:

sum = 0.0

and

mean = sum(hist)

even if both could exist side by side it would be very confusing IMO.

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


Re: Object Not Callable, float?

2009-11-29 Thread Carl Banks
On Nov 29, 8:14 pm, "W. eWatson"  wrote:
> Ben Finney wrote:
> > "W. eWatson"  writes:
>
> >> "C:\Sandia_Meteors\Sentinel_Development\Development_Sentuser+Utilities\sentuser\sentuser_20090103+hist.py",
> >> line 467, in ShowHistogram
> >>     mean = sum(hist)
> >> TypeError: 'float' object is not callable
>
> > It means you're calling an object of type ‘float’. The line where it
> > occurred shows that you're accessing that object through the name ‘sum’,
> > which means you've bound the name ‘sum’ to a float object.
>
> >> for the code:
> >> --
> >>         sum = 0.0
>
> > Here you clobber the existing binding of ‘sum’, binding it to the float
> > value 0.0.
>
> >>         avg = 0.0
> >>         nplt_bins = 32
> >>         for i in range(len(hist)):
> >> #             msg = "%5d %6d\n" % (i,hist[i])
> >>             msg = "%5d %6d\n" % (i,hist[i])
> >>             sum = sum + hist[i]
>
> > Here you keep re-binding the name ‘sum’ to new float objects of
> > different value.
>
> >>             text.insert( END, msg )
> >>         for i in range(len(hist)):
> >>             avg = avg + (i*hist[i]/sum)
>
> >>         mean = sum(hist)   <-- faulty line
>
> > Here you try to call the object referenced by the name ‘sum’, which is a
> > float object.
>
> >> hist is a list of 256 integers. What does float have to do with this?
>
> > You explicitly bound the name ‘sum’ to an object of type ‘float’.
>
> > Solution: Choose names wisely, and if you want to use a built-in name
> > like ‘sum’ for its built-in putpose, don't clobber that binding before
> > using it.
>
> Yikes. Thanks very much. Python seems to act unlike other language in
> which words like float are reserved. I'll use asum.

That "float" isn't reserved isn't the problem here since the conflict
occurred with the word sum, which is a function.  Most languages I
know don't reserve the names of functions.  For instance you can't do
this in C:

int printf = 1;
printf("%d\n", printf);

Python doesn't reserve the names of types either, which is a little
uncommon (but not unheard of), so that can be a gotcha.


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


Re: Creating a local variable scope.

2009-11-29 Thread Terry Reedy

markolopa wrote:



so "domain" should not exist in my namespace since I have no
information associated to "domain" only to "self.domains". Python
should allow me to write safe code!


Leaving iteration names bound after loop exit is a feature. If you do 
not like it, explicitly unbind it.


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


Re: Object Not Callable, float?

2009-11-29 Thread W. eWatson

Ben Finney wrote:

"W. eWatson"  writes:


"C:\Sandia_Meteors\Sentinel_Development\Development_Sentuser+Utilities\sentuser\sentuser_20090103+hist.py",
line 467, in ShowHistogram
mean = sum(hist)
TypeError: 'float' object is not callable


It means you're calling an object of type ‘float’. The line where it
occurred shows that you're accessing that object through the name ‘sum’,
which means you've bound the name ‘sum’ to a float object.


for the code:
--
sum = 0.0


Here you clobber the existing binding of ‘sum’, binding it to the float
value 0.0.


avg = 0.0
nplt_bins = 32
for i in range(len(hist)):
# msg = "%5d %6d\n" % (i,hist[i])
msg = "%5d %6d\n" % (i,hist[i])
sum = sum + hist[i]


Here you keep re-binding the name ‘sum’ to new float objects of
different value.


text.insert( END, msg )
for i in range(len(hist)):
avg = avg + (i*hist[i]/sum)

mean = sum(hist)   <-- faulty line


Here you try to call the object referenced by the name ‘sum’, which is a
float object.


hist is a list of 256 integers. What does float have to do with this?


You explicitly bound the name ‘sum’ to an object of type ‘float’.

Solution: Choose names wisely, and if you want to use a built-in name
like ‘sum’ for its built-in putpose, don't clobber that binding before
using it.

Yikes. Thanks very much. Python seems to act unlike other language in 
which words like float are reserved. I'll use asum.

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


Re: Best strategy for overcoming excessive gethostbyname timeout.

2009-11-29 Thread MrJean1
Take a look at function timelimited in this recipe

 

/Jean


On Nov 29, 8:08 am, r0g  wrote:
> r0g wrote:
> > r0g wrote:
> >> Gabriel Genellina wrote:
> >>> En Fri, 27 Nov 2009 22:35:36 -0300, r0g 
> >>> escribió:
>
>  gethostbyname ignores setdefaulttimeout.
>
>  How big a job is it to use non-blocking sockets to write a DNS lookup
>  function with a customisable timeout? A few lines? A few hundred? I'd
> > 
>
> > As usual, everything is working beautifully until I try to make it work
> > with windows!
>
> > Turns out signals.SIGALRM is Unix only and I want to run on both
> > platforms so I have done as the docs suggested and tried to convert the
> > code to use threading.Timer to trigger an exception if the DNS lookup is
> > taking too long.
>
> Actually none of that was necessary in the end. Digging into the pydns
> source to debug the 30 second pause I happened across the timeout parameter!
>
> >>> result = ping.do_one( "google.com", 5 )
>
> ""
>
> Phew, that simplifies thing a lot! :)
>
> Roger.

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


Re: Noobie python shell question

2009-11-29 Thread Chris Rebert
On Sun, Nov 29, 2009 at 7:53 PM, Tim Chase
 wrote:

> (as an aside, is there a way to get a local/global variable from a string
> like one can fetch a variable from a class/object with getattr()?  Something
> like getattr(magic_namespace_here, "hello") used in the above context?  I
> know it can be done with eval(), but that's generally considered unsafe
> unless you vet your input thoroughly)

locals()["hello"]  and  globals()["hello"], respectively

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Noobie python shell question

2009-11-29 Thread Dave Angel

tuxsun wrote:

I've been working in the shell on and off all day, and need to see if
a function I defined earlier is defined in the current shell I'm
working in.

Is there a shell command to get of list of functions I've defined?

TIA!

P.S. If it makes a difference, I'm using the shell from within IDLE,
but once in a while I will use the python shell in a Bash console.


  
dir() is the answer to the question you ask.  It'll display the entire 
global context.  But usually there's a better way.  If you think you 
previously defined a function

def myfunc()


just enter myfunc at the prompt (without parentheses).  It should tell 
you it's a function, or undefined.



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


Re: Feature request: String-inferred names

2009-11-29 Thread Brad Harms
On Sun, Nov 29, 2009 at 7:49 PM, Lie Ryan  wrote:

> On 11/29/2009 12:22 PM, The Music Guy wrote:
>
>> When I first started seeing @ show up in Python code, I said "what the
>> heck is that? It looks so weird and _ugly_.I would never try to mess
>> with that." But I started seeing it more and more, so I asked #python
>> what it was. They told me about decorators, so I looked it up in the
>> docs, and I thought the idea was interesting. It took me a while to
>> figure out exactly how they worked--and judging from messages I've
>> seen in #python a number of people have the same trouble understanding
>> them.
>>
>
> And we don't want a second flood of users asking about foo.$bar.
>
>
>  My point is that any particular syntax would look ugly to you only
>> because you haven't seen it in use enough, and haven't used it enough
>> yourself.
>>
>
> You're absolutely right, and I have *never needed* to use the plain
> getattr/setattr/delattr enough to even bother considering a syntax that
> already looks ugly at first sight. For @decorators, everyone used it *often
> enough* BEFORE it turned into a syntax that the ugly syntax is justified and
> become "acceptable". If you can find a syntax that doesn't look ugly at
> first sight +0, fine by me; otherwise -1, I don't want to be forced to read
> an ugly syntax for a feature that I don't use often enough. It's not just
> the syntax, the necessity+syntax don't add up well.
>
>
> > But of course you haven't--it's not currently a valid
>
>> syntax. However, the ugliness would seem to go away after the syntax
>> had been in use for a while. And again, the EXACT syntax of the
>> feature can be adjusted until its "just right".
>>
>
> In so far, your definition of adjusting only means something around
> "[a-zA-Z0-9_]+\.[^a-zA-Z0-9_][<{(\[]?[a-zA-Z0-9_]+[>})\]]?"



> that class of syntax is ugly; some are more acceptable (e.g. obj.[arg]) the
> old thread have spawned better alternatives than that class of syntax.
>


>  As for my specific use case, it's somewhat difficult to explain.
>>
>
> You know that:
> If the implementation is hard to explain it's a bad idea.
> -- Zen of Python --
>
> right?
>
>
> > The
>
>> general idea was to isolate a pattern that I spotted repeated in
>> several unrelated parts of my project. The pattern manifested itself
>> as a set of 4-5 methods and/or properties on a class whose objects
>> were designed to work in conjunction with other objects that fit a
>> particular behavior. These other objects had methods and properties
>> that were designed to interact with the first type of object in a
>> similar but--how should I say--"inverted" fashion.
>>
>
> Do you mean something like this?
>
> class A(object):
>@property
>def the_b(self):
>return self._b
>@the_b
>def the_b(self, new_b):
>self._b = new_b
>self._b._a = self
>
> class B(object):
>@property
>def the_a(self):
>return self._a
>@the_a
>def the_a(self, new_a):
>self._a = new_a
>self._a._b = self
>
> am I getting you right? If not, please elaborate and give an example of
> what you actually meant.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


I understand that in all likelyhood this feature won't be added to Python
anytime soon, if at all. But I'd like to continue this discussion anyway;
it's been enlightening for me. Even though I don't agree with the views of
some of the people who've replied, I like the insight. And anyway, I think
that if the syntax were already present, people would feel a lot more
positively about it; it's the idea of adding it in so late in the game that
people seem to have a problem with for the most part.

It doesn't seem like anybody besides inhahe has actually realized that my
proposition is actually different than PEP 363 in a subtle but crucial way.
It's not _literally_ a shorthand for accessing the *attr functions; that's
just the way I originally assumed it would be used most often. However, I
have since realized that the syntax is more powerful than I originally
thought: ANYWHERE that a name appeared--this includes function names, class
names, function parameters, possibly even module names--could be replaced by
an expression that would be evaluated to the name. That makes the use of any
kind of brackets, except maybe , bad options, as it would
conflict with [lists,] {dicts,} (tuples,) or generic parenthesized
(expressions). There must be a unique indicator of some kind, something that
isn't already in use by the interpreter. That way there is no possible way
that it could get confused with another syntactical construct.

So you could do something like this:


def class_factory(this, that)
get_that = "get_"+that
set_that = "set_"+that
_that = "_" + that

class $this (object):

def __init__(self, $that = None):
self.$_that = $that

def $get_that (self):
return self.$_t

Re: Feature request: String-inferred names

2009-11-29 Thread Carl Banks
On Nov 28, 3:38 am, The Music Guy  wrote:
> On Nov 28, 3:07 am, Lie Ryan  wrote:
> > If you use it a lot, it is likely 1) you have abused class syntax for
> > what should have been a dict or 2) what you need is to override
> > __getattr__/__getattribute__ and __setattr__
>
> Oh boy...here we go. :|
>
> Please listen. In all the time I've spent in the coding community
> (that's at least 7 years) and especially since I started paying
> attention to the Python community (2 years), I have noticed a trend:
> When one coder does something that another cannot understand,
> frequently the other will assume the former is not only doing things
> wrong, but is doing them _blatantly_ wrong. I have caught myself
> making that very assumption many times in the past, and I've tried
> hard to build up an immunity against the impulse to make that
> assumption. At this point, I don't even believe in such a thing as a
> universal "wrong way" and a "right way" to code that applies to every
> circumstance. The way to solve a problem depends on the problem. When
> it comes to coding, there is not an absolute "right" way or "wrong"
> way--unless we're talking about, say, stealing closed source code
> without permission, or deliberately coding in a way that will cause
> problems for the end user (like causing memory clogs or buffer
> overflows and whatnot).
>
> All of this can be determined through common sense.

Another thing that can be determined through common sense is that if
you have object that you are calling getattr and setattr on so much
that you think you need special syntax, you should have been using a
dict.


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


Re: Feature request: String-inferred names

2009-11-29 Thread Carl Banks
On Nov 26, 3:43 pm, The Music Guy  wrote:
> That aside, I still feel that a new syntax would be a better solution
> than a new class. And, anyway, what I'm proposing isn't *quite* the
> same as what Ben North proposed. Ben's idea was *strictly* to create
> shorthand syntax to the getattr/setattr/delattr in the context of
> specific objects. What I'm suggesting could be more accurately
> described as a namespace-neutral transformation of the value of an
> expression into a name. So if "bar" is the value of foo, then when the
> interpreter sees  $foo, it reads bar.

This transformation isn't possible in Python.  Python has seperate
compile and run times, and the value of a variable (like foo) isn't
known at compile time, but it would have to be known at compile time
for the interpreter to "see" the value of that variable ("bar" in this
example).

Therefore, to get the effect you want, the evaluation of foo would
have to be delayed until run time.  The interpreter would "see" $foo,
and explicitly change it to bar.  But that leads to another problem.

Local variables (in CPython at least) are converted to index lookups
during the compile phase, for efficiency reasons.  Python doesn't use
the name of a the local variable at run time at all, and you can't
dynamically create local variables.  Thus, to use your syntax proposal
with local variables you would have to accept two concessions:

1. You could not use $foo to dynamically create a new local variable;
foo would have to evaluate to the name of a local variable that
already exists.

2. You would take a significant performance hit.

Furthermore, this would introduce a bad analogical inconsistency into
the language.  If you can write foo.$bar=1 to create a new attribute,
you'd expect to be able to write $bar=1 to create a new local
variable, but you can't.

These issues are significant, and given that a proposal for just
computed attributes that didn't have these issues was already
rejected, I would say your proposal would have absolutely no chance,
even if there hadn't been a moratorium on new syntax.


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


Re: Noobie python shell question

2009-11-29 Thread Tim Chase

tuxsun wrote:

I've been working in the shell on and off all day, and need to see if
a function I defined earlier is defined in the current shell I'm
working in.

Is there a shell command to get of list of functions I've defined?


yesish...you can use dir() from the prompt to see the bound names 
in a given scope:


 >>>  dir()
 ['__builtins__', '__doc__', '__name__']
 >>> def hello(who='world'):
 ... print "Hello, %s" % who
 ...
 >>> dir()
 ['__builtins__', '__doc__', '__name__', 'hello']
 >>> x = 42
 >>> dir()
 ['__builtins__', '__doc__', '__name__', 'hello', 'x']

however AFAIK, there's no readily accessible way to get the 
*definition* of that function back (other than scrolling back 
through your buffer or readline history) and it takes a bit more 
work to determine whether it's a callable function, or some other 
data-type.


 >>> callable(x)
 False
 >>> callable(hello)
 True

(as an aside, is there a way to get a local/global variable from 
a string like one can fetch a variable from a class/object with 
getattr()?  Something like getattr(magic_namespace_here, "hello") 
used in the above context?  I know it can be done with eval(), 
but that's generally considered unsafe unless you vet your input 
thoroughly)


-tkc


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


Re: Creating a local variable scope.

2009-11-29 Thread Dave Angel

markolopa wrote:


===

arg_columns =]
for domain in self.domains:
i =elf.get_column_index(column_names, domain.name)
col =olumn_elements[i]
if len(col) !=en(val_column):
ValueError('column %s has not the same size as the value
column %s'
   % (column_names[i], self.name))
arg_columns.append(col)

[...]

value_dict =}
for i, val_str in enumerate(val_column):
arg_name_row =c[i] for c in arg_columns]
args =domain[name] for name in arg_name_row]
value_dict[tuple(args)] =loat(val_str)
repo[self.name] =alue_dict

===

The bug is corrected replacing the line

args =domain[name] for name in arg_name_row]

by

args =domain[name] for name, domain in zip(arg_name_row,
self.domains)]

so "domain" should not exist in my namespace since I have no
information associated to "domain" only to "self.domains". Python
should allow me to write safe code!

Antoher 15 minutes lost because of that Python "feature"... Is it only
me???

  
Yep, I think so.  You're proposing a much more complex scoping rule, 
where if a variable already exists before entering a loop, then the loop 
uses that existing variable, but if not, it creates its own local one 
and destroys it when exiting the loop.  That's the exact opposite of 
what function definitions do, which already makes it confusing.


I think if you had your wish, you'd find that you had more exceptions 
where you had to pre-declare things, than the times when you avoided the 
bugs you describe.  I don't like languages that make me write extra 
stuff 100 times, to save one instance of extra debugging.  If Python 
already required declarations, then I might buy your arguments.  But it 
wouldn't be Python.

Thanks for your comment!
Marko

  


In your particular case, the compiler couldn't guess whether you used 
the first loop to decide which domain to use in the second loop, or 
whether you accidentally reused the same name without giving it a new 
value in the new loop.  If you need to use the same name, you could 
always follow your loops with the del statement to invalidate the name.



DaveA

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


Re: Exec Statement Question

2009-11-29 Thread Dave Angel

Victor Subervi wrote:

Hi;
I have the following line of code:

exec('%s()' % table)

where 'table' is a variable in a for loop that calls variables from another
script. I've made it so that it only calls one variable. I know for a fact
that it's calling that variable in the script because it found errors in
that script. I've tried to have it return the following:

print 'hi'
return 'hi'

It doesn't return anything. No errors are thrown because the code evaluates.
I don't know how to capture the output. I would like to do something like:

print exec(...)

or

var = exec(...)

but of course those options don't work. Suggestions?
TIA,
Victor

  
exec is a statement, and statements don't have "return values."   It's 
not a function, so there are no parentheses in its syntax, either.  exec 
is also a technique of last resort;  there's nearly always a 
better/safer/faster way to accomplish what you might want, but of course 
you don't say what that is.


As for "returning" values, exec by default uses the same global space as 
your app, so you can just modify a global variable in your "called" code 
and use it afterwards.


abc = 42
value = 12
exec "abc = %d" % value
print abc

DaveA


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


ANN: GMPY 1.11rc1 is available

2009-11-29 Thread casevh
Everyone,

I'm pleased to annouce that a new version of GMPY is available.
GMPY is a wrapper for the MPIR or GMP multiple-precision
arithmetic library. GMPY 1.11rc1 is available for download from:

http://code.google.com/p/gmpy/

In addition to support for Python 3.x, there are several new
features in this release:

- Even faster conversion to/from Python longs.
- Performance improvements by reducing function overhead.
- Performance improvements by improved caching.
- Support for cdivmod, fdivmod, and tdivmod.
- Unicode strings are accepted on Python 2.x and 3.x.
- Fixed regression in GMPY 1.10 where True/False were no
  longer recognized.

Comments on provided binaries

The 32-bit Windows installers were compiled with MinGW32 using MPIR
1.3.0rc3 and will automatically recognize the CPU type and use code
optimized for the CPU at runtime. The 64-bit Windows installers were
compiled Microsoft's SDK compilers using MPRI 1.3.0rc3. Detailed
instructions are included if you want to compile your own binary.

Future plans

On releasing the GIL: I have compared releasing the GIL versus the
multiprocessing module and the multiprocessing module offers better
and more predictable performance for embarrassingly parallel tasks
than releasing the GIL. If there are requests, I can add a compile-
time option to enable threading support but it is unlikely to
become the default.

On mutable integers: The performance advantages of mutable integers
appears to be 20% to 30% for some operations. I plan to add a new
mutable integer type in the next release of GMPY. If you want to
experiment with mutable integers now, GMPY can be compiled with
mutable version of the standard 'mpz' type. Please see the file
"mutable_mpz.txt" for more information.

Please report any issues!

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


Noobie python shell question

2009-11-29 Thread tuxsun
I've been working in the shell on and off all day, and need to see if
a function I defined earlier is defined in the current shell I'm
working in.

Is there a shell command to get of list of functions I've defined?

TIA!

P.S. If it makes a difference, I'm using the shell from within IDLE,
but once in a while I will use the python shell in a Bash console.

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


Re: Object Not Callable, float?

2009-11-29 Thread Ben Finney
"W. eWatson"  writes:

> "C:\Sandia_Meteors\Sentinel_Development\Development_Sentuser+Utilities\sentuser\sentuser_20090103+hist.py",
> line 467, in ShowHistogram
> mean = sum(hist)
> TypeError: 'float' object is not callable

It means you're calling an object of type ‘float’. The line where it
occurred shows that you're accessing that object through the name ‘sum’,
which means you've bound the name ‘sum’ to a float object.

> for the code:
> --
> sum = 0.0

Here you clobber the existing binding of ‘sum’, binding it to the float
value 0.0.

> avg = 0.0
> nplt_bins = 32
> for i in range(len(hist)):
> # msg = "%5d %6d\n" % (i,hist[i])
> msg = "%5d %6d\n" % (i,hist[i])
> sum = sum + hist[i]

Here you keep re-binding the name ‘sum’ to new float objects of
different value.

> text.insert( END, msg )
> for i in range(len(hist)):
> avg = avg + (i*hist[i]/sum)
>
> mean = sum(hist)   <-- faulty line

Here you try to call the object referenced by the name ‘sum’, which is a
float object.

> hist is a list of 256 integers. What does float have to do with this?

You explicitly bound the name ‘sum’ to an object of type ‘float’.

Solution: Choose names wisely, and if you want to use a built-in name
like ‘sum’ for its built-in putpose, don't clobber that binding before
using it.

-- 
 \   “To have the choice between proprietary software packages, is |
  `\  being able to choose your master. Freedom means not having a |
_o__)master.” —Richard M. Stallman, 2007-05-16 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Object Not Callable, float?

2009-11-29 Thread W. eWatson

Here's an traceback error msg I get.

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__
return self.func(*args)
  File 
"C:\Sandia_Meteors\Sentinel_Development\Development_Sentuser+Utilities\sentuser\sentuser_20090103+hist.py", 
line 467, in ShowHistogram

mean = sum(hist)
TypeError: 'float' object is not callable

for the code:
--
sum = 0.0
avg = 0.0
nplt_bins = 32
for i in range(len(hist)):
# msg = "%5d %6d\n" % (i,hist[i])
msg = "%5d %6d\n" % (i,hist[i])
sum = sum + hist[i]
text.insert( END, msg )
for i in range(len(hist)):
avg = avg + (i*hist[i]/sum)

mean = sum(hist)   <-- faulty line
mean = mean/256.0
-end

hist is a list of 256 integers. What does float have to do with this?
--
http://mail.python.org/mailman/listinfo/python-list


Re: semantics of ** (unexpected/inconsistent?)

2009-11-29 Thread Ben Finney
Lie Ryan  writes:

> I generally do not expect operator precedence to be reliable at all

Have another read of the thread. The OP's confusion was not over
operator precedence, but over how names resolve to values in
expressions.

-- 
 \  “Life does not cease to be funny when people die any more than |
  `\  it ceases to be serious when people laugh.” —George Bernard Shaw |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: semantics of ** (unexpected/inconsistent?)

2009-11-29 Thread Lie Ryan

On 11/30/2009 12:38 PM, Esmail wrote:

Thanks all!! I get it now :-)

It helped to have a number of different explanations, thanks
for taking the time to post. Much appreciated.


I generally do not expect operator precedence to be reliable at all 
except for:


+ - (binary ops, not the unary)
* /
**

for other operators I would have explicit parens. It's too much work to 
remember the rest of the precedence sheet.

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


Re: Feature request: String-inferred names

2009-11-29 Thread Lie Ryan

On 11/29/2009 12:22 PM, The Music Guy wrote:

When I first started seeing @ show up in Python code, I said "what the
heck is that? It looks so weird and _ugly_.I would never try to mess
with that." But I started seeing it more and more, so I asked #python
what it was. They told me about decorators, so I looked it up in the
docs, and I thought the idea was interesting. It took me a while to
figure out exactly how they worked--and judging from messages I've
seen in #python a number of people have the same trouble understanding
them.


And we don't want a second flood of users asking about foo.$bar.


My point is that any particular syntax would look ugly to you only
because you haven't seen it in use enough, and haven't used it enough
yourself.


You're absolutely right, and I have *never needed* to use the plain 
getattr/setattr/delattr enough to even bother considering a syntax that 
already looks ugly at first sight. For @decorators, everyone used it 
*often enough* BEFORE it turned into a syntax that the ugly syntax is 
justified and become "acceptable". If you can find a syntax that doesn't 
look ugly at first sight +0, fine by me; otherwise -1, I don't want to 
be forced to read an ugly syntax for a feature that I don't use often 
enough. It's not just the syntax, the necessity+syntax don't add up well.


> But of course you haven't--it's not currently a valid

syntax. However, the ugliness would seem to go away after the syntax
had been in use for a while. And again, the EXACT syntax of the
feature can be adjusted until its "just right".


In so far, your definition of adjusting only means something around 
"[a-zA-Z0-9_]+\.[^a-zA-Z0-9_][<{(\[]?[a-zA-Z0-9_]+[>})\]]?"


that class of syntax is ugly; some are more acceptable (e.g. obj.[arg]) 
the old thread have spawned better alternatives than that class of syntax.



As for my specific use case, it's somewhat difficult to explain.


You know that:
If the implementation is hard to explain it's a bad idea.
 -- Zen of Python --

right?

> The

general idea was to isolate a pattern that I spotted repeated in
several unrelated parts of my project. The pattern manifested itself
as a set of 4-5 methods and/or properties on a class whose objects
were designed to work in conjunction with other objects that fit a
particular behavior. These other objects had methods and properties
that were designed to interact with the first type of object in a
similar but--how should I say--"inverted" fashion.


Do you mean something like this?

class A(object):
@property
def the_b(self):
return self._b
@the_b
def the_b(self, new_b):
self._b = new_b
self._b._a = self

class B(object):
@property
def the_a(self):
return self._a
@the_a
def the_a(self, new_a):
self._a = new_a
self._a._b = self

am I getting you right? If not, please elaborate and give an example of 
what you actually meant.

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


Re: semantics of ** (unexpected/inconsistent?)

2009-11-29 Thread Esmail

Thanks all!! I get it now :-)

It helped to have a number of different explanations, thanks
for taking the time to post. Much appreciated.

Cheers,
Esmail

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


Re: semantics of ** (unexpected/inconsistent?)

2009-11-29 Thread Mel
Esmail wrote:
> Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
> [GCC 4.3.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> 
> 
>  >>> -3**2
> -9
> 
>  >>> x = -3
> 
>  >>> x**2
> 9
>  >>>
> 
> I would have expected the same result in both cases.
> 
> Initially I would have expected -3**2 to yield 9, but I can accept
> that ** binds tighter than the unary -, but shouldn't the results
> be consistent regardless if I use a literal or a variable?

When you say ** binds tighter than unary -, you're also saying that -3 isn't 
a literal: it's an expression.  Try

y=3
-y**2

Mel.


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


Re: semantics of ** (unexpected/inconsistent?)

2009-11-29 Thread Alf P. Steinbach

* Esmail:

Ok, this is somewhat unexpected:

Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.


 >>> -3**2
-9

 >>> x = -3

 >>> x**2
9
 >>>

I would have expected the same result in both cases.

Initially I would have expected -3**2 to yield 9, but I can accept
that ** binds tighter than the unary -, but shouldn't the results
be consistent regardless if I use a literal or a variable?


It is.

>>> -3**2
-9
>>> x = 3
>>> -x**2
-9
>>>

:-)


I guess you expect your expression "x**2" to somehow be evaluated as "-3**2". 
But x doesn't contain text, it contains an integer value that presumably (I 
don't know) is represented in the binary number system, so it's evaluated as 
"(-3)**2". If x contained text and was evaluated as such, pure text replacement, 
then you should be able to write 2 x and have that evaluated as "2 -x"...



Cheers & hth.,

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


Re: python and vc numbers

2009-11-29 Thread Gregory Ewing

Daniel Dalton wrote:

what function/module should
I use to figure out what tty my program was invoked from?


Here's one way:

% python
Python 2.5 (r25:51908, Apr  8 2007, 22:22:18)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.popen("tty").read()
'/dev/ttyp1\n'

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


Re: [Edu-sig] teaching python using turtle module

2009-11-29 Thread kirby urner
On Sun, Nov 29, 2009 at 2:51 PM, Edward Cherlin  wrote:

<< snip >>

> Drunkard's Walk.
>

If our think tank (isepp.org) could have gotten permission, we'd have
used that Monopoly guy (looks kinda like Planters peanut guy) randomly
walking on like some chess board with a lamp post (reminds of Narnia).
 We don't have that kind of dough though, so just do this conceptually
(conceptual art).

>> Are there any other situations, using turtle, that these
>> structures would be natural?
>
> Recent versions of TA contain stack instructions: push, pop, read,
> clear. Your students might find it interesting to program Forth
> instructions in TA or Python. This has practical applications in
> implementing and porting virtual machines such as Parrot and the VMs
> in Smalltalk and I-APL.
>
> There is plenty more where this came from. You would also be welcome
> to adapt the Python source code for TA tiles to your environment.
>

I recall Alan Kay communicating Seymour Papert's sense that having "an
explicit receiver" was an OK development.  What he meant by that, in
Smalltalk terms, is that the original Logo had what I'd call a
"context turtle" in that FORWARD or RIGHT were w/r to a given Turtle
one didn't need to mention explicitly, like what else could one mean?

With Python and other object oriented implementations, one first gives
birth to a turtle, creates an instance, as in:

>>> someturtle = Turtle()

That's binding a name to a turtle object (giving some turtle object a
name) and then controlling said turtle through the API using dot
notation against the name, e.g. someturtle.forward(10) or
someturtle.right(90).

What you get from this is, of course, the possibility of multiple
turtles, each with its own pen color, visibility, other properties of
self-hood.

This gets showcased in the default demo (in Windows, just double click
on turtle.py in the Lib subdirectory):
http://www.flickr.com/photos/17157...@n00/4145780784/
(using Gregor's 3.1 code just minutes ago)

IronPython also has access to the .NET turtle library:
http://www.flickr.com/photos/mfoord/3104991233/
(not my computer)

I suppose I'm only bringing this up to (a) name drop about being in a
meeting with Alan Kay (with Guido and Mark Shuttleworth among others)
and (b) to remind readers that Logo and turtle art, or the art of
programming with turtles, are orthogonal axes.

Logo as a language has also been extended considerably, as has the
richness of the environment.  Some of these are commercial,
proprietary offerings.

Some of these feature "spatial turtles" in a "turtle tank" i.e. each
turtle is more like a biplane in a WWI dogfight (Snoopy vs. Red
Baron), with all those extra degrees of freedom (roll, pitch, yaw).

Python's turtle module is not, repeat not, an implementation of Logo
in the Python language.  It's an implementation of turtle graphics on
a Tk canvas in the Python language.

You'll also find a turtle module in wxPython such as in PythonCard by
Kevin Altis.
http://pythoncard.sourceforge.net/samples/turtle.html

I think Gregor is right to see turtle.py as an easy way to implement
an Objects First approach, consistent with a more generic approach to
math concepts (vectors, polynomials, polyhedra) as objects (types),
extending the OO rubric.

We teach maths as extensible type systems that advance through the
invention of new types, not just as systems evolving through a
progression of proved theorems from fixed axioms.

Kirby


>> thanks,
>> Brian Blais
>> --
>> Brian Blais
>> bbl...@bryant.edu
>> http://web.bryant.edu/~bblais
>>
>>
>>
>> ___
>> Edu-sig mailing list
>> edu-...@python.org
>> http://mail.python.org/mailman/listinfo/edu-sig
>>
>>
>
>
>
> --
> Edward Mokurai (默雷/धर्ममेघशब्दगर्ज/دھرممیگھشبدگر ج) Cherlin
> Silent Thunder is my name, and Children are my nation.
> The Cosmos is my dwelling place, the Truth my destination.
> http://www.earthtreasury.org/
> ___
> Edu-sig mailing list
> edu-...@python.org
> http://mail.python.org/mailman/listinfo/edu-sig
>



-- 
>>> from mars import math
http://www.wikieducator.org/Martian_Math
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: slightly OT: Python BootCamp

2009-11-29 Thread Terry Reedy

J wrote:

Ok... so I've been re-teaching myself python, as it's been several
years since I last really used it.  And in the midst of this, my
contracting company came up to me on Friday and asked if I'd be
interested in filling a last minute vacancy in this:

http://www.otg-nc.com/python-bootcamp

It's a week long Python Bootcamp.  I figured, free class, a week where
I'll not have to actually go to work, AND I'll get paid, sure!

So I was just wondering if any of you have attended this one, or one
like it, and what your impressions were.  I've attended a few before,
and found them widely different.  The RH300, for example, was
blisteringly fast and really just touches on things, so if you don't
already know Red Hat inside and out, you'll never survive.  The VMWare
VCP courses, on the other hand, were fairly languid by contrast and
seemed to flow in a less frantic state.

So I figured this would be the place to ask.

And if it matters, I do have an educational background in programming
(VB, C++, C, Java, etc) but my professional background has mostly been
limited to Bash, OCCASIONAL C, and now a touch of Python, so I am not
new to programming and OO programming, just not as proficient as I
would like to be...


The list of topics seems to cover basic + intermediate issues.
If you do go, perhaps you could review it here.
Same for people who have attended other Python training courses, of course.

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


Re: semantics of ** (unexpected/inconsistent?)

2009-11-29 Thread Ben Finney
Esmail  writes:

> Brian J Mingus wrote:
> >
> >
> >
> > I think you answered your own question. 3**2 comes first in the
> > order of operations, followed by the negation.
>
> No, that's not the problem, I'm ok with the operator precedence of - vs **
>
> My problem is why I don't get the same result if I use the literal -3
> or a variable that contains -3 (x in my example).

You seem to be confusing the values, which (in this case) are numbers,
with their incidental representation in Python code, which is literal
expressions in text. Perhaps the following dissection will help:

>>> -3**2

The expression ‘-3**2’ is evaluated, and a single value is the result.
In that expression, there are two operators: the unary-minus operator
and the exponential operator. There are two values as parameters in the
expression: the natural number three, and the natural number two.

>>> x = -3

The expression ‘-3’ is evaluated, and a single value is the result. That
value has an internal representation of “the integer that is three less
than zero”. It is *not* the sequence of characters that you see in the
Python code; it is a number.

The name ‘x’ is then bound to that value.

>>> x**2

The expression ‘x**2’ is evaluated, and a single value is the result. In
that expression, there is *one* operator: the exponential operator.
There is no unary-minus operator in the expression. There are two values
as parameters in the expression: the value referenced by the name ‘x’
which is the integer negative-three, and the natural number two.

I hope that explains the difference in behaviour.

-- 
 \  “I don't like country music, but I don't mean to denigrate |
  `\  those who do. And for the people who like country music, |
_o__)denigrate means ‘put down’.” —Bob Newhart |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a local variable scope.

2009-11-29 Thread Alf P. Steinbach

* markolopa:


On 18 Sep, 10:36, "markol...@gmail.com"  wrote:

On Sep 11, 7:36 pm, Johan Grönqvist  wrote:

I find several places in my code where I would like tohavea variable
scope that is smaller than the enclosing function/class/module definition.

This is one of the single major frustrations I have with Python and an
important source of bugs for me. Here is a typical situation


Here is another bug that I just got. Twenty minutes lost to find it...

class ValueColumn(AbstractColumn):
def __init__(self, name, header, domain_names):
if type(domain_names) != tuple:
raise ValueError('a tuple of domain names must be given')
for name in domain_names:
if type(name) != str:
raise ValueError('a tuple of domain names must be
given')
self.domain_names = domain_names
super(ValueColumn, self).__init__(name, header)

The upper class was initialized with the wrong name, because the for
loop to check
domain_names used "name" which is also the argument to be passed.

If is an old thread but I am reopening to present real situation where
this Python
"feature" bothers me...


I think if one could somehow declare names as const (final, readonly, whatever) 
then that would cover the above plus much more.



Cheers,

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


Re: Feature request: String-inferred names

2009-11-29 Thread Terry Reedy

The Music Guy wrote:


When I first started seeing @ show up in Python code, I said "what the
heck is that? 


For future reference, PySymbols.html at
http://code.google.com/p/xploro/downloads/list
answers all such symbol questions.

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


Re: semantics of ** (unexpected/inconsistent?)

2009-11-29 Thread The Music Guy
It's just like in algebra. You evaluate exponents before the - which, after
all, is just another way to write -1, or times-negative-one. However, a
variable with a negative value is not the same as a value that is being
multiplied by a negative.

-3 ** 2   =   (-1)(3)^(2)  in algebraic terms. Exponents first, then
multiplication.

However,

x ** 2 = (x)^(2) = (-3)^(2)

regardless of the value of x which, in this case, is -3. When you multiply a
negative by itself, you get a positive.

In short, the ** operator appears to have a higher precedence than the -
operator, based on your results.


On Sun, Nov 29, 2009 at 6:39 PM, Esmail  wrote:

> Ok, this is somewhat unexpected:
>
> Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
> [GCC 4.3.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>
>
> >>> -3**2
> -9
>
> >>> x = -3
>
> >>> x**2
> 9
> >>>
>
> I would have expected the same result in both cases.
>
> Initially I would have expected -3**2 to yield 9, but I can accept
> that ** binds tighter than the unary -, but shouldn't the results
> be consistent regardless if I use a literal or a variable?
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: semantics of ** (unexpected/inconsistent?)

2009-11-29 Thread Martin v. Löwis
>> I think you answered your own question. 3**2 comes first in the order
>> of operations, followed by the negation.
> 
> No, that's not the problem, I'm ok with the operator precedence of - vs **
> 
> My problem is why I don't get the same result if I use the literal -3 or
> a variable that contains -3 (x in my example).

There is no literal -3 in Python, only a literal (+)3, see

http://docs.python.org/reference/lexical_analysis.html#integer-and-long-integer-literals

So -3**2 means -(3**2) == -9.

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


Re: semantics of ** (unexpected/inconsistent?)

2009-11-29 Thread Colin W.

On 29-Nov-09 19:50 PM, Chris Rebert wrote:

On Sun, Nov 29, 2009 at 4:39 PM, Esmail  wrote:

Ok, this is somewhat unexpected:

Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.



-3**2

-9


x = -3



x**2

9




I would have expected the same result in both cases.

Initially I would have expected -3**2 to yield 9, but I can accept
that ** binds tighter than the unary -, but shouldn't the results
be consistent regardless if I use a literal or a variable?


_No_, because using the variable evaluates "-3" as a unit separately
by itself, before the exponentiation ever occurs; it's the same as the
difference between (-3)**2 and -3**2.
Python is not a concatenative programming language[*]; you can't
directly textually replace a variable with its value and expect to get
the same result from an expression. For instance, in this case, you
need to add the parentheses.

Cheers,
Chris
--
http://blog.rebertia.com

[*] http://en.wikipedia.org/wiki/Concatenative_language

See the Operator Order of Precedence:
http://docs.python.org/reference/expressions.html#summary

Parentheses permit the user to vary the precedence.

Colin W.

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


Re: semantics of ** (unexpected/inconsistent?)

2009-11-29 Thread Esmail

Chris Rebert wrote:


_No_, because using the variable evaluates "-3" as a unit separately
by itself, before the exponentiation ever occurs; it's the same as the
difference between (-3)**2 and -3**2.
Python is not a concatenative programming language[*]; you can't
directly textually replace a variable with its value and expect to get
the same result from an expression. For instance, in this case, you
need to add the parentheses.

Cheers,
Chris
--
http://blog.rebertia.com

[*] http://en.wikipedia.org/wiki/Concatenative_language


Wow .. never heard of Concatenative_languages languages before or the
distinction you make. Your distinction explains the behavior, but I
find it somewhat counter-intuitive. (I use the Python interpreter frequently
for small calculations - otherwise I'd never have realized this)

Thanks,

Esmail

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


Re: Variables with cross-module usage

2009-11-29 Thread Terry Reedy

Dennis Lee Bieber wrote:


In these languages, the names always refer to the same location.
Python confuses matters by having names that don't really refer to
location, but are attached to the objects.


In everyday life and natural languages, names refer to people, other 
objects, roles, and only occasionally to places that can be occupied. I 
could claim that it is classical computer languages that confuse by 
restricting names to locations in a linear sequence. You are just used 
to the straightjacket ;-).


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


Re: semantics of ** (unexpected/inconsistent?)

2009-11-29 Thread Esmail

Brian J Mingus wrote:




I think you answered your own question. 3**2 comes first in the order of 
operations, followed by the negation.


No, that's not the problem, I'm ok with the operator precedence of - vs **

My problem is why I don't get the same result if I use the literal -3 or
a variable that contains -3 (x in my example).


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


Re: semantics of ** (unexpected/inconsistent?)

2009-11-29 Thread Chris Rebert
On Sun, Nov 29, 2009 at 4:39 PM, Esmail  wrote:
> Ok, this is somewhat unexpected:
>
> Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
> [GCC 4.3.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>
>
 -3**2
> -9
>
 x = -3
>
 x**2
> 9

>
> I would have expected the same result in both cases.
>
> Initially I would have expected -3**2 to yield 9, but I can accept
> that ** binds tighter than the unary -, but shouldn't the results
> be consistent regardless if I use a literal or a variable?

_No_, because using the variable evaluates "-3" as a unit separately
by itself, before the exponentiation ever occurs; it's the same as the
difference between (-3)**2 and -3**2.
Python is not a concatenative programming language[*]; you can't
directly textually replace a variable with its value and expect to get
the same result from an expression. For instance, in this case, you
need to add the parentheses.

Cheers,
Chris
--
http://blog.rebertia.com

[*] http://en.wikipedia.org/wiki/Concatenative_language
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a local variable scope.

2009-11-29 Thread Steve Howell
On Nov 29, 4:26 pm, markolopa  wrote:
> Less than 3 hours have passed since my last post and got yet another
> bug that could be prevented if Python had the functionality that other
> languages have to destroy variables when a block ends. Here is the
> code:
>
> =
>
> arg_columns = []
> for domain in self.domains:
>     i = self.get_column_index(column_names, domain.name)
>     col = column_elements[i]
>     if len(col) != len(val_column):
>         ValueError('column %s has not the same size as the value
> column %s'
>                    % (column_names[i], self.name))
>         arg_columns.append(col)
>
> [...]
>
> value_dict = {}
> for i, val_str in enumerate(val_column):
>     arg_name_row = [c[i] for c in arg_columns]
>     args = [domain[name] for name in arg_name_row]
>     value_dict[tuple(args)] = float(val_str)
> repo[self.name] = value_dict
>
> =
>
> The bug is corrected replacing the line
>
>     args = [domain[name] for name in arg_name_row]
>
> by
>
>     args = [domain[name] for name, domain in zip(arg_name_row,
> self.domains)]
>
> so "domain" should not exist in my namespace since I have no
> information associated to "domain" only to "self.domains". Python
> should allow me to write safe code!
>
> Antoher 15 minutes lost because of that Python "feature"... Is it only
> me???
>

I occasionally make the error you make, but I think the real problem
you are having is lack of attention to detail.  If name collisions are
a common problem for you, consider writing shorter methods or develop
the habit of using more descriptive variable names.  In the code
above, you could have easily cleaned up the namespace by extracting a
method called get_arg_columns().  Having to spend 15 minutes tracking
down a bug usually indicates that you are not being systematic in your
thinking.  If you are rushing too much, slow down.  If you are tired,
take a break.  If you make the same mistake twice, commit to yourself
not to make it a third time.  Also, test your methods one at a time
and get them rock solid before writing more code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: semantics of ** (unexpected/inconsistent?)

2009-11-29 Thread Brian J Mingus
On Sun, Nov 29, 2009 at 5:39 PM, Esmail  wrote:

> Ok, this is somewhat unexpected:
>
> Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
> [GCC 4.3.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>
>
> >>> -3**2
> -9
>
> >>> x = -3
>
> >>> x**2
> 9
> >>>
>
> I would have expected the same result in both cases.
>
> Initially I would have expected -3**2 to yield 9, but I can accept
> that ** binds tighter than the unary -, but shouldn't the results
> be consistent regardless if I use a literal or a variable?
>

I think you answered your own question. 3**2 comes first in the order of
operations, followed by the negation.

>>> (-3)**2
9
>>> 3**2
9
>>> -3**2
-9
-- 
http://mail.python.org/mailman/listinfo/python-list


semantics of ** (unexpected/inconsistent?)

2009-11-29 Thread Esmail

Ok, this is somewhat unexpected:

Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.


>>> -3**2
-9

>>> x = -3

>>> x**2
9
>>>

I would have expected the same result in both cases.

Initially I would have expected -3**2 to yield 9, but I can accept
that ** binds tighter than the unary -, but shouldn't the results
be consistent regardless if I use a literal or a variable?



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


Re: Creating a local variable scope.

2009-11-29 Thread markolopa
Hi Lie!

On Nov 29, 11:11 pm, Lie Ryan  wrote:
> here is another bug you might have if python have an "even-more-local"
> scope:
>
> while True:
>      s = raw_input("enter something: ")
>      if s not in ('q', 'quit', 'exit'): break
> print s
>
> if the while block has become its own namespace; print s would generate
> NameError.

This bug you show is completely different, because it is not
dangerous: you get the error and you realise directly how to fix it.

> It is one or the other, you will have problem caused by "namespace too
> small" or "namespace too big". Neither is better than the other, so
> python's two-level name resolution (global and local level) is the
> simplest one, is the better one.

I would be much happier with the smaller namespace. To fix the code
that you show I would impose

s = None
while True:
 s = raw_input("enter something: ")
 if s not in ('q', 'quit', 'exit'): break
print s

The use in a block of variables created in an inner block is (for me
at least) more an exception than a rule.

Less than 3 hours have passed since my last post and got yet another
bug that could be prevented if Python had the functionality that other
languages have to destroy variables when a block ends. Here is the
code:

=

arg_columns = []
for domain in self.domains:
i = self.get_column_index(column_names, domain.name)
col = column_elements[i]
if len(col) != len(val_column):
ValueError('column %s has not the same size as the value
column %s'
   % (column_names[i], self.name))
arg_columns.append(col)

[...]

value_dict = {}
for i, val_str in enumerate(val_column):
arg_name_row = [c[i] for c in arg_columns]
args = [domain[name] for name in arg_name_row]
value_dict[tuple(args)] = float(val_str)
repo[self.name] = value_dict

=

The bug is corrected replacing the line

args = [domain[name] for name in arg_name_row]

by

args = [domain[name] for name, domain in zip(arg_name_row,
self.domains)]

so "domain" should not exist in my namespace since I have no
information associated to "domain" only to "self.domains". Python
should allow me to write safe code!

Antoher 15 minutes lost because of that Python "feature"... Is it only
me???

Thanks for your comment!
Marko
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Edu-sig] teaching python using turtle module

2009-11-29 Thread Brian Blais

On Nov 29, 2009, at 17:51 , Edward Cherlin wrote:


If you use the Python-programmable tile in Turtle Art in Sugar, or
Smalltalk in the Turtle Graphics in Etoys, it's even better.


I'll have to check this out.


sequences, where I can use a conditional to stop when the turtle would
go off the screen.


ah, good idea.


or
functions that return values, as opposed to "procedures" like:
def square(length):
forward(length)
right(90)
forward(length)
right(90)
forward(length)
right(90)
forward(length)
right(90)


Surely you mean

repeat(4)
   forward(length)
   right(90)



surely I don't mean.  :)

that's not python.  I'd do:

def square(length):
for i in range(4):
forward(length)
right(90)

but there isn't much difference with such a simple shape.  obviously,  
as one continued, the for-loop method would be clearer.




If-statements could possibly be used with some sort of random  
behavior (if

rand()<0.5 ...).


Drunkard's Walk.



yes, that was the kind of thing I was thinking about.


thanks!

bb


--
Brian Blais
bbl...@bryant.edu
http://web.bryant.edu/~bblais



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


Re: [Edu-sig] teaching python using turtle module

2009-11-29 Thread Edward Cherlin
On Sun, Nov 29, 2009 at 11:34, Brian Blais  wrote:
> Hello,
> I was just playing with the turtle module, and thought it was an interesting
> way to augment the introduction to python (I teach college students, who
> haven't had any programming).  It's a great way to introduce functions,
> for-loops, and general program structures.

If you use the Python-programmable tile in Turtle Art in Sugar, or
Smalltalk in the Turtle Graphics in Etoys, it's even better. I have
been doing presentations on teaching Python in elementary schools, and
working on how to teach basic Computer Science ideas. You can use an
if-then-else to initialize a stream in Python for the first pass, and
get a value at each pass thereafter. The logic can be either in the TA
or the Python.

> After a bit of playing, I realized that I couldn't think of many exaples
> which use turtle with conditional structures (if- and while- statements),

Repeat is used much more often. but of course we can provide examples
of any behavior you like. I like to use the turtle to generate
sequences, where I can use a conditional to stop when the turtle would
go off the screen. Fibonacci numbers, for example, or exponentials.
Similarly for spirals of various types. Simple cases like those are
easy to do in TA, while more complex sequences could use Python. There
are several fractal examples using loops provided with Sugar on a
Stick, including variations on Siepinksi constructions, and the Koch
Snowflake.

When I can get the code for reading the color of a dot on the screen
into the programmable tile, I can program a toy Turing machine, with
an array of dots as the transition table, and a line of dots as the
tape.

> or
> functions that return values, as opposed to "procedures" like:
> def square(length):
>     forward(length)
>     right(90)
>     forward(length)
>     right(90)
>     forward(length)
>     right(90)
>     forward(length)
>     right(90)

Surely you mean

repeat(4)
   forward(length)
   right(90)

> If-statements could possibly be used with some sort of random behavior (if
> rand()<0.5 ...).

Drunkard's Walk.

> Are there any other situations, using turtle, that these
> structures would be natural?

Recent versions of TA contain stack instructions: push, pop, read,
clear. Your students might find it interesting to program Forth
instructions in TA or Python. This has practical applications in
implementing and porting virtual machines such as Parrot and the VMs
in Smalltalk and I-APL.

There is plenty more where this came from. You would also be welcome
to adapt the Python source code for TA tiles to your environment.

> thanks,
> Brian Blais
> --
> Brian Blais
> bbl...@bryant.edu
> http://web.bryant.edu/~bblais
>
>
>
> ___
> Edu-sig mailing list
> edu-...@python.org
> http://mail.python.org/mailman/listinfo/edu-sig
>
>



-- 
Edward Mokurai (默雷/धर्ममेघशब्दगर्ज/دھرممیگھشبدگر ج) Cherlin
Silent Thunder is my name, and Children are my nation.
The Cosmos is my dwelling place, the Truth my destination.
http://www.earthtreasury.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a local variable scope.

2009-11-29 Thread Lie Ryan

On 11/30/2009 8:12 AM, markolopa wrote:

Hi,

On 18 Sep, 10:36, "markol...@gmail.com"  wrote:

On Sep 11, 7:36 pm, Johan Grönqvist  wrote:

I find several places in my code where I would like tohavea variable
scope that is smaller than the enclosing function/class/module definition.


This is one of the single major frustrations I have with Python and an
important source of bugs for me. Here is a typical situation


Here is another bug that I just got. Twenty minutes lost to find it...

class ValueColumn(AbstractColumn):
 def __init__(self, name, header, domain_names):
 if type(domain_names) != tuple:
 raise ValueError('a tuple of domain names must be given')
 for name in domain_names:
 if type(name) != str:
 raise ValueError('a tuple of domain names must be
given')
 self.domain_names = domain_names
 super(ValueColumn, self).__init__(name, header)

The upper class was initialized with the wrong name, because the for
loop to check
domain_names used "name" which is also the argument to be passed.

If is an old thread but I am reopening to present real situation where
this Python
"feature" bothers me...



here is another bug you might have if python have an "even-more-local" 
scope:


while True:
s = raw_input("enter something: ")
if s not in ('q', 'quit', 'exit'): break
print s

if the while block has become its own namespace; print s would generate 
NameError.


It is one or the other, you will have problem caused by "namespace too 
small" or "namespace too big". Neither is better than the other, so 
python's two-level name resolution (global and local level) is the 
simplest one, is the better one.

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


Re: Variables with cross-module usage

2009-11-29 Thread Nitin Changlani.
Thanks Dennis and Steve,

This explains it all! I will discard using one.a and use one.myList[0]
directly, instead. I really appreciate your patience and the elaboration of
the concept.

Warm Regards,
Nitin Changlani.

On Sun, Nov 29, 2009 at 1:02 AM, Steven D'Aprano <
st...@remove-this-cybersource.com.au> wrote:

> On Sat, 28 Nov 2009 22:18:11 -0500, Nitin Changlani wrote:
>
> > Thanks for the reply MRAB, Rami, Matt and Mel,
> >
> > I was assuming that since one.myList0] = one.a, the change in one.a will
> > ultimately trickle down to myList[0] whenever myList[0] is printed or
> > used in an expression. It doesn't come intuitively to me as to why that
> > should not happen. Can you kindly suggest what is the correct way to go
> > about it?
>
>
> You are confusing *names* and *objects*. The presence or absence of a
> module qualifier is irrelevant, so for simplicity I will avoid it. I will
> use ` ` quotation marks to refer to names, to avoid confusing them with
> strings.
>
>
> The Python statement
>
> a = "some text"
>
> creates a name `a` which is bound to the object "some text".
>
> myList[0] = a
>
> stores the object bound to the name `a` to the first position of myList,
> not the name itself. So myList[0] ends up being "some text", but it has
> no idea whether it came from the name `a` or somewhere else.
>
> Then when you execute:
>
> a = "different text"
>
> the name `a` is bound to the object "different text". But this doesn't
> affect myList[0] at all, because you're not changing the object "some
> text" -- strings are immutable and can't be changed.
>
>
>
> --
> Steven
> --
> http://mail.python.org/mailman/listinfo/python-list
>

> Thanks for the reply MRAB, Rami, Matt and Mel,
>
> I was assuming that since one.myList0] = one.a, the change in one.a will
> ultimately trickle down to myList[0] whenever myList[0] is printed or used
> in an expression. It doesn't come intuitively to me as to why that should
> not happen. Can you kindly suggest what is the correct way to go about it?
>

   First you understand that no common programming language behaves
this way... It's not just Python.

   It's just more subtle in Python.

   In classical languages "one.myList[0]" represents a location (in
this case, think of a room of file cabinets). "one" is a cabinet in the
room; myList is a drawer in the cabinet; [0] is a folder in the drawer.
and "a" is another drawer.

   In this classical language "one.myList[0] = one.a" means "open up
the drawer a in cabinet one, make a COPY of what it contains, and put
that copy into the [0] folder inside drawer myList in cabinet one.

   In these languages, the names always refer to the same location.
Python confuses matters by having names that don't really refer to
location, but are attached to the objects.

   "one" is a name attached to an object (the module). "a" is a name
"inside" the object "one" which is attached to some other object,
whatever it is. Similarly, "myList" is a name attached to an object (an
indexed list or a keyed dictionary). "[0]" is a "name" (the index or
key) into the object the name "myList" is attached to.

   "one.myList[0] = one.a" means "find the object with the name 'one.a'
attached to it, and attach then name 'one.myList[0]' to the same object"
Later, if you do "one.a = something", you say "find the object with name
'something' and attach the name 'one.a' to it" -- it is, in effect, the
name that is moved from object to object -- no copy is made.



--
   Wulfraed Dennis Lee Bieber   KD6MOG
   wlfr...@ix.netcom.com
HTTP://wlfraed.home.netcom.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Number of distinct substrings of a string [continuation]

2009-11-29 Thread Bearophile
n00m:

> I suspect that building of Suffix Tree would
> be a big exec.time-consuming overhead

In C/D/C++ there are ways to allocate memory in smarter ways, using
pools, arenas, stacks, freelists, etc. With that, using a compact
encoding of tree nodes (there are many different tricks to reduce
space used by a suffix tree), you can go fast enough. Probably a basic
implementation too will suffice in many cases :-)

Anyway, you may try a pure-Python2.x implementation:
http://suffixtree.googlecode.com/files/suffixtree-0.1.py
If you find time & will to try to use that (or similar code) to
improve your Python solution to the problem 99, you can show us the
code here...

Bye,
bearophile
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a local variable scope.

2009-11-29 Thread markolopa
Hi,

On 18 Sep, 10:36, "markol...@gmail.com"  wrote:
> On Sep 11, 7:36 pm, Johan Grönqvist  wrote:
> > I find several places in my code where I would like tohavea variable
> > scope that is smaller than the enclosing function/class/module definition.
>
> This is one of the single major frustrations I have with Python and an
> important source of bugs for me. Here is a typical situation

Here is another bug that I just got. Twenty minutes lost to find it...

class ValueColumn(AbstractColumn):
def __init__(self, name, header, domain_names):
if type(domain_names) != tuple:
raise ValueError('a tuple of domain names must be given')
for name in domain_names:
if type(name) != str:
raise ValueError('a tuple of domain names must be
given')
self.domain_names = domain_names
super(ValueColumn, self).__init__(name, header)

The upper class was initialized with the wrong name, because the for
loop to check
domain_names used "name" which is also the argument to be passed.

If is an old thread but I am reopening to present real situation where
this Python
"feature" bothers me...

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


Exec Statement Question

2009-11-29 Thread Victor Subervi
Hi;
I have the following line of code:

exec('%s()' % table)

where 'table' is a variable in a for loop that calls variables from another
script. I've made it so that it only calls one variable. I know for a fact
that it's calling that variable in the script because it found errors in
that script. I've tried to have it return the following:

print 'hi'
return 'hi'

It doesn't return anything. No errors are thrown because the code evaluates.
I don't know how to capture the output. I would like to do something like:

print exec(...)

or

var = exec(...)

but of course those options don't work. Suggestions?
TIA,
Victor
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: * for generic unpacking and not just for arguments?

2009-11-29 Thread Tim Chase

The feature is available in Python 3.x:


a, b, *c = 1, 2, 3, 4, 5
a, b, c

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

a, *b, c = 1, 2, 3, 4, 5
a, b, c

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


This is a nice feature of 3.x but I'm disappointed (especially in 
light of the move to make more things iterators/generators), that 
the first form unpacks and returns a list instead returning the 
unexhausted generator.  There are times I've wanted to write 
something like


  def powers_of_n(n=2):
p = 0
while True:
  yield n ** p
  p += 1

  def linear(i=0, step=1):
while True:
  yield i
  i += step

  CONST_A, CONST_B, CONST_C, *_ = linear()
  OPT_A, OPT_B, OPT_C, *_ = powers_of_n()

because adding another CONST or OPT becomes trivial (just add it 
to the list of names).  I currently have to do something like


  CONST_A, CONST_B, CONST_C = range(3)

and then remember to bump up my range() parameter when I create a 
new value on the left.  It's not bad to see here, but I often 
have times where N>60 constants and tweaking something in an 
alphabetically sorted list may require scrolling to see/remember 
the range() change.



However, because 3.x tries to make a list out of it, this doesn't 
help me at all because my generator is infinite.  Boo.



Diez Roggisch gave me a beautiful (okay, the implementation code 
is a bit ugly, but the final product's simplicity achieves 
elegance) solution to my similar want for 2.x here:


http://www.mail-archive.com/python-list@python.org/msg87022.html

-tkc




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


teaching python using turtle module

2009-11-29 Thread Brian Blais

Hello,

I was just playing with the turtle module, and thought it was an  
interesting way to augment the introduction to python (I teach  
college students, who haven't had any programming).  It's a great way  
to introduce functions, for-loops, and general program structures.


After a bit of playing, I realized that I couldn't think of many  
examples which use turtle with conditional structures (if- and while-  
statements), or functions that return values, as opposed to  
"procedures" like:


def square(length):
forward(length)
right(90)
forward(length)
right(90)
forward(length)
right(90)
forward(length)
right(90)


If-statements could possibly be used with some sort of random  
behavior (if rand()<0.5 ...).  Are there any other situations, using  
turtle, that these structures would be natural?




thanks,

Brian Blais

--
Brian Blais
bbl...@bryant.edu
http://web.bryant.edu/~bblais



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


Re: * for generic unpacking and not just for arguments?

2009-11-29 Thread Lie Ryan

On 11/30/2009 1:25 AM, Russell Warren wrote:



Maybe it's just that * is strictly for arguments, and trying it for
generic tuple unpacking is abuse (which is down the corridor in 12A).


Because (1, 2, *x) == (1, 2, 3, 4) is not tuple unpacking [!]


Tuple unpacking is related with assignment, e.g.:
a, b, c = 1, 2, 3

In python 3, there is the extended tuple unpacking:
>>> a, b, *c = [1, 2, 3, 4, 5]
>>> # a = 1; b = 2; c = [3, 4, 5]
>>> a, *b, c = [1, 2, 3, 4, 5]
>>> # a = 1; b = [2, 3, 4]; c = 5


If I remember correctly, the idea of (1, 2, *x) to mean (1, 2) + x has 
been discussed before, and rejected as well.

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


Re: debugger on system with Python 2 and 3

2009-11-29 Thread Nir
rpdb2 should be compatible with Python 3.x.
And once you start a debugging session with rpdb2 (running with Python
3.x)
you can attach to it from a winpdb instance (running with Python 2.x)


On Nov 29, 2:29 pm, Yo Sato  wrote:
> If there's no other choice I don't mind using winpdb, but it is
> installed (through Yum) under Python2 library and invokes Py2 at
> default... Don't quite know how to adapt it to Py3 or install the
> right version under the right directory, yet. It seems as if some
> environmental variable change is necessary. On the whole it doesn't
> seem that there's much support in the third-party debuggers in general
> as yet...
>
> In the meantime I might ask if it is possible to adapt pydb (or
> perhaps, IDLE) for Py3. Might be just a change in a env variable or
> two...
>
> Yo


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


Re: delete column content

2009-11-29 Thread Vlastimil Brom
2009/11/29 Francesco Pietra :
> Hi:
> How to replace with blank the single-character in column 21 of a pdb
> file (in pdb numbering it is column 22). Attached is an incomplete
> exercise with slices. I am unable to get real plain text with gmail.
>
> Thanks for help
>
> francesco pietra
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>

Do you mean something like

>>> line="abcdefghijklmnopqrstuvwxyz"
>>> line[:21]+line[22:]
'abcdefghijklmnopqrstuwxyz'

?

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


Re: Installing Python 2.5 with Python 2.6

2009-11-29 Thread pranav
On Nov 29, 11:06 pm, pranav  wrote:
> Hi,
> I used to develop applications on Google AppEngine SDK (which supports
> Python 2.5) on my Fedora 10.
> I upgraded to Fedora 12 recently and it has Python 2.6.
> Unfortunately, some things are breaking up with the SDK. Here is the
> tracehttp://dpaste.com/hold/126668/
> I had been suggested by the  AppEngine guys to install Python 2.5.
> So i wanted to know --  is it safe to install Python 2.5 alongwith
> Python 2.6? How will i configure my OS to use Python 2.6 (which was
> there already) and the SDK to use Python 2.5, which i will install
> new?
> Any other issues/suggestions/comments anyone?

here, http://wtanaka.com/linux/f11#python25 . this page talks about
installing Python 2.5 on fedora 11. Anyone knows a similar resource
for Python 2.5 on Fedora 12?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: delete column content

2009-11-29 Thread Diez B. Roggisch

Francesco Pietra schrieb:

Hi:
How to replace with blank the single-character in column 21 of a pdb
file (in pdb numbering it is column 22). Attached is an incomplete
exercise with slices. I am unable to get real plain text with gmail.

Thanks for help


Wasn't the help you already got a few days ago sufficient?

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


Re: Filling in a tuple from unknown size list

2009-11-29 Thread Ned Deily
In article 
,
 inhahe  wrote:
> maybe that thing in python 3 that someone mentioned is the answer, but
> otherwise i always think Python should admit something like this:
> 
> a, b, c, *d = list
> 
> i.e. if list were [1,2,3,4,5], you'd get a=1, b=2, c=3, d=[4, 5]

Extended iterable unpacking (http://www.python.org/dev/peps/pep-3132/) 
is implemented in python 3.

$ python3
Python 3.1.1 (r311:74543, Aug 24 2009, 18:44:04) 
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a, b, c, *d = [1,2,3,4,5]
>>> d
[4, 5]

-- 
 Ned Deily,
 n...@acm.org

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


delete column content

2009-11-29 Thread Francesco Pietra
Hi:
How to replace with blank the single-character in column 21 of a pdb
file (in pdb numbering it is column 22). Attached is an incomplete
exercise with slices. I am unable to get real plain text with gmail.

Thanks for help

francesco pietra
# Sample line
# Slice indexes cut to the left of the corrresponding item index
#   1 2 3 4 5 6
# 012345678901234567890123456789012345678901234567890123456789012345 ...
# ATOM  1  N   LEU A   1 153.242  64.673  95.851  0.00  0.00   N


data = open('in.pdb', 'r')
outp = open('out.pdb', 'w')

for L in data:
   if L[21] == 'A':
 L = L[ ???
   outp.write(L)
-- 
http://mail.python.org/mailman/listinfo/python-list


Installing Python 2.5 with Python 2.6

2009-11-29 Thread pranav
Hi,
I used to develop applications on Google AppEngine SDK (which supports
Python 2.5) on my Fedora 10.
I upgraded to Fedora 12 recently and it has Python 2.6.
Unfortunately, some things are breaking up with the SDK. Here is the
trace http://dpaste.com/hold/126668/
I had been suggested by the  AppEngine guys to install Python 2.5.
So i wanted to know --  is it safe to install Python 2.5 alongwith
Python 2.6? How will i configure my OS to use Python 2.6 (which was
there already) and the SDK to use Python 2.5, which i will install
new?
Any other issues/suggestions/comments anyone?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: * for generic unpacking and not just for arguments?

2009-11-29 Thread Russell Warren
On Nov 29, 11:09 am, Christian Heimes  wrote:
> The feature is available in Python 3.x:
>
> >>> a, b, *c = 1, 2, 3, 4, 5
> >>> a, b, c
> (1, 2, [3, 4, 5])
> >>> a, *b, c = 1, 2, 3, 4, 5
> >>> a, b, c
>
> (1, [2, 3, 4], 5)

Interesting... especially the recognition of how both ends work with
the "a, *b, c" example.  That is some funky syntax.  And it goes to a
list instead of a tuple now, I see.

It is also the opposite of what I was considering, although I expect
it goes both ways like it does for functions?  The given python 3.0
example is on the LHS with * packing many-to-one while unpacking (like
*args inside a function), whereas I was referring to RHS-style
unpacking where * explodes/unpacks one-to-many (like passing *args
_to_ a function).

I've steered clear of 3.x so far, but it looks like I'll have to give
it a whirl if only to avoid asking irrelevant questions!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: staticmethod not callable? (trying to make a Singleton metaclass..)

2009-11-29 Thread Gabriel Genellina

En Sun, 29 Nov 2009 10:25:21 -0300, inhahe  escribió:


I'm trying to come up with a system for singletons, where I don't have to
modify anything for an individual class except to define __metaclass__  
or,

if possible, to inherit another class.

I want it to raise an error if making a duplicate instance of a class is
attempted, rather than to return the same object,


(I won't comment on the usefulness of such approach...)


class Singleton(type):
  def __new__(meta, classname, bases, classDict):
@staticmethod
def nonewinst(*args, **kwargs):
  raise ValueError("Can't make duplicate instance of singleton " +
classname)
@staticmethod
def newoldnew(obj):
  return obj
oldnew = classDict.get("__new__", newoldnew)
@staticmethod
def newnew(obj, *args, **kwargs):
  o = oldnew(obj, *args, **kwargs)
  obj.__new__ = nonewinst
  return o
classDict["__new__"] = newnew
return type.__new__(meta, classname, bases, classDict)


__new__ is a classmethod, not a staticmethod.


a little bit of experimentation revealed that apparently even functions
defined within a method become class methods,





so i tried making them all
static methods.



Why do you insist on static methods?


however, python is strange to me when it comes to methods
and the self parameter.  i mean i understand a function being free of the
class so that the 'self' parameter doesn't mean anything in particular
unless you explicitly pass it an instance.  and i understand the method
being bound to an object so that when it's called its self parameter is
automatically sent the instance.  but python seems to have this  
in-between
mode where sometimes a function isn't particularly bound to an instance  
but

if you try to pass the wrong kind of instance to 'self' it'll complain,
which gets annoying, and i don't understand how its binding works.


Do you mean this error?
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unbound method foo() must be called with X instan
ce as first argument (got Y instance instead)

This kind of check was removed in Python 3; ClassName.method_name yields a  
plain function, not an unbound method as in 2.x



but
anyway, the problem i'm currently having with the code might not even be
related to that..because here's the error I'm getting:


from funcs import Singleton
class A:

...   __metaclass__ = Singleton
...

b = A()

Traceback (most recent call last):
  File "", line 1, in 
  File "c:\python25\funcs.py", line 68, in newnew
o = oldnew(obj, *args, **kwargs)
TypeError: 'staticmethod' object is not callable


That's true: instances of the staticmethod type are not callable.


i'm not that experienced with metaclasses, but it seems to me that
something's obviously going fubar here because at that point oldnew  
should

be the function newoldnew (since class A doesn't have a __new__ defined)
which is clearly defined right there with a staticmethod decorator, and
first of all, functions *should* be callable, and secondly, why is my  
object

a 'staticmethod' object just because I used a decorator on it?  it would
seem it should be a function, so i tested it like this:


class A:

...   @staticmethod
...   def b(): pass
...

type(A.b)



in that case, using @staticmethod returns a function.  i have nfi why  
it's

different in my Singleton class.

oh, and thirdly, staticmethod is a decorator and decorators are  
callables so

even given that for some mysterious reason it's a staticmethod object i
don't know why it's not callable.  so that's pretty confusing.  can  
anyone

clear this up for me?  thanks..


staticmethod is a type:

py> staticmethod


Used as a decorator, it's like this:

def b(): pass
b = staticmethod(b)

so b is an staticmethod instance. You can confirm this looking into the  
class:


py> A.__dict__['b']

py> A.b


A staticmethod instance is a descriptor; its __get__ method is invoked to  
resolve A.b (or getattr(A, "b")). If you retrieve it directly, you get the  
staticmethod object which is not callable:


py> A.__dict__['b']()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'staticmethod' object is not callable

Going back to your original goal, your code at the top is really a mess. I  
would not even use a metaclass. If you want to avoid creating more than  
one instance, just record the fact that you created it in the class  
constructor, __new__:


class HardSingleton(object):
"Only one instance of its subclasses may be created ever"
_created = False
def __new__(cls, *args, **kw):
if cls._created:
raise ValueError("Can't make duplicate instance of singleton  
%s" % cls.__name__)

result = super(HardSingleton, cls).__new__(cls, *args, **kw)
cls._created = True
return result

class A(HardSingleton):
def __init__(self):
print "A"

[ANNC] pybotwar-0.7

2009-11-29 Thread Lee Harr

pybotwar is a fun and educational game where players
write computer programs to control simulated robots.

http://pybotwar.googlecode.com/


pybotwar uses pybox2d for the physical simulation.
It can be run in text-only mode -- useful for longer
tournaments -- or use pyqt or pygame for a graphical
interface and visualization of the action.

pybotwar is released under GPLv3.


Changes in pybotwar-0.7:
    - pybox2d-2.0.2b1 compatibility (latest pybox2d release)
    - decouple view modules so unused graphic modules are not required
    - added new "pinged" sensor to detect when robot is seen by others
    - randomize order robots are handled each tick
    - PyQt4 interface improvements
    - new battle dialog to select combatants
    - internal text editor improvements
    - allow multiple open editor windows
    - do a few simple checks on robot programs when saving

  
_
Windows Live: Keep your friends up to date with what you do online.
http://www.microsoft.com/middleeast/windows/windowslive/see-it-in-action/social-network-basics.aspx?ocid=PID23461::T:WLMTAGL:ON:WL:en-xm:SI_SB_1:092010
-- 
http://mail.python.org/mailman/listinfo/python-list


Auto net surfing

2009-11-29 Thread joao abrantes
How can I make a python program that votes on certain polls ? Atm I am using
ClientForm to fill forms but the polls that I found are always of the type =
"hidden" and I don't know how to do it.

I would also want to do a python program that would vote on a website. For
example, if I go to this url http://games.top.org/ultima-online/ while I am
on this site: http://www.uo.burstfire.net/ that site will win a vote... if i
got to the same url but while i am on this site http://www.drw.ru/en/ the
vote goes to this one. Well how can I make python give me the vote for a
certain site? I don't know how this vote systems work sorry for the noob
questions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best strategy for overcoming excessive gethostbyname timeout.

2009-11-29 Thread r0g
r0g wrote:
> r0g wrote:
>> Gabriel Genellina wrote:
>>> En Fri, 27 Nov 2009 22:35:36 -0300, r0g 
>>> escribió:
>>>
 gethostbyname ignores setdefaulttimeout.

 How big a job is it to use non-blocking sockets to write a DNS lookup
 function with a customisable timeout? A few lines? A few hundred? I'd
> 
> 
> As usual, everything is working beautifully until I try to make it work
> with windows!
> 
> Turns out signals.SIGALRM is Unix only and I want to run on both
> platforms so I have done as the docs suggested and tried to convert the
> code to use threading.Timer to trigger an exception if the DNS lookup is
> taking too long.

Actually none of that was necessary in the end. Digging into the pydns
source to debug the 30 second pause I happened across the timeout parameter!

>>> result = ping.do_one( "google.com", 5 )
""

Phew, that simplifies thing a lot! :)

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


Re: Implementation of Book Organization tool (Python2.[x])

2009-11-29 Thread Aahz
In article <4b0a06b...@dnews.tpgi.com.au>,
Lie Ryan   wrote:
>
>Python dictionary is stored in memory and closing the program ==
>deleting the database. You can pickle dictionary; and this might be
>sufficient for quick and dirty, low-volume purpose. Pickled dictionary
>is the least portable solution; only python program can open a
>pickled dictionary and even different versions of python may have
>incompatibilities.

While that last sentence is technically true, I've never seen it be an
issue for this kind of application when changing versions upward.  IOW,
pickles from previous versions of Python can almost always be read.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

The best way to get information on Usenet is not to ask a question, but
to post the wrong information.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: * for generic unpacking and not just for arguments?

2009-11-29 Thread Christian Heimes
Russell Warren wrote:
> but the code below is not?
> 
 x = (3, 4)
 (1, 2, *x) == (1, 2, 3, 4)
> Traceback (most recent call last):
>   File "", line 1, in 
> invalid syntax: , line 1, pos 8
> 
> Why does it only work when unpacking arguments for a function?  Is it
> because the code below is preferred, and more readable?
> 
 x = (3, 4)
 (1, 2) + x == (1, 2, 3, 4)
> True
> 
> I've rooted around to see if there is an answer already and found some
> threads going way back to 1998 (!!), but can't find a concise answer
> as to why it is limited to args.

The feature is available in Python 3.x:

>>> a, b, *c = 1, 2, 3, 4, 5
>>> a, b, c
(1, 2, [3, 4, 5])
>>> a, *b, c = 1, 2, 3, 4, 5
>>> a, b, c
(1, [2, 3, 4], 5)

Christian

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


Re: * for generic unpacking and not just for arguments?

2009-11-29 Thread inhahe
On Sun, Nov 29, 2009 at 10:40 AM, Mel  wrote:
> Russell Warren wrote:
>
>> Maybe it's just that * is strictly for arguments, and trying it for
>> generic tuple unpacking is abuse (which is down the corridor in 12A).
>
> I'd agree with that.  It's a feature of function calls, not a feature of
> sequence types, so that you can handle a set of function arguments as a
> bunch, and apply them when you want.
>
> The other function call feature that sequence types don't do is
>
> a, b, c = **{'b':3, 'c':a, 'a':c}
>
>
>        Mel.
>
>

that's wicked
i'd go for that
i'd definitely go for the a, b, *c = lst   syntax though
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: slightly OT: Python BootCamp

2009-11-29 Thread Aahz
In article ,
J   wrote:
>On Sun, Nov 29, 2009 at 03:57, Carl Banks  wrote:
>> On Nov 28, 6:15=A0pm, J  wrote:
>>>
>>> http://www.otg-nc.com/python-bootcamp
>>>
>>> It's a week long Python Bootcamp.
>>
>>
>> I'm surprised they're able to fill out 5 days with intensive training
>> on Python.
>
>but on a serious note, your comment was why I was asking... I was
>trying to figure out just how much python you could teach in an
>assumed 40 hours... but it's also supposed to be probably 80%
>(arbitrary semi-educated guess) hands on coding, and if that's the
>case, each 30 minute project could well be 45 minutes to an hour
>depending on how fast people type, how familiar they are with actually
>properly formatting code, etc...

There are a couple of ways you can get benefit out of this even if the
class itself isn't that useful for you:

* Spend time working on Python projects from your job without the
pressure of being at work

* Help the other people in the class learn Python, which will cement your
knowledge
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

The best way to get information on Usenet is not to ask a question, but
to post the wrong information.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Number of distinct substrings of a string [continuation]

2009-11-29 Thread n00m
Tested both my codes against
a random string of length = 1.

===

from random import choice
s = ''
for i in xrange(1):
s += choice(('a','b','c','d','e','f'))

===

C++: ~0.28s
Python: ~0.48s

PS
I suspect that building of Suffix Tree would
be a big exec.time-consuming overhead
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mysqldb cursor returning type along with result ?

2009-11-29 Thread Lie Ryan

On 11/30/2009 12:14 AM, Paul O'Sullivan wrote:

Just taken to Python (2.5)and started to look at some DB cursor stuff
using MySQL.  Anyway, after creating a query that in MySQL that has a
result set of decimals I find that the cursor in python after a
fetchall() returns a tuple that contains the following ::

((Decimal("101.10"),), (Decimal("99.32"),), (Decimal("97.95"),),
(Decimal("98.45"),), (Decimal("97.39"),), (Decimal("97.91"),), (Decimal
("98.08"),), (Decimal("97.73"),))

as such :
   sum(result)
fails with "TypeError: unsupported operand type(s) for +: 'int' and
'tuple'"

How do I either get the resultset back as 'float' or convert the
returned tuple to 'floats'.?


I believe it returned decimal.Decimal() objects. You can do arithmetic 
with decimal.Decimals, so:


sum(x[0] for x in result)
--
http://mail.python.org/mailman/listinfo/python-list


Re: slightly OT: Python BootCamp

2009-11-29 Thread Steve Howell
On Nov 28, 6:15 pm, J  wrote:
> Ok... so I've been re-teaching myself python, as it's been several
> years since I last really used it.  And in the midst of this, my
> contracting company came up to me on Friday and asked if I'd be
> interested in filling a last minute vacancy in this:
>
> http://www.otg-nc.com/python-bootcamp
>
> It's a week long Python Bootcamp.  I figured, free class, a week where
> I'll not have to actually go to work, AND I'll get paid, suore!
>

I have never been, but it seems like a no-brainer to attend.  Even if
the class totally sucks, which I doubt, you will also have the
opportunity to network with people with similar interests.

If your ONLY objective in life was to learn Python, then I would
recommend just hitting the books.

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


Re: xmlrpc idea for getting around the GIL

2009-11-29 Thread Aahz
In article <4b0b07a1$0$22159$9b622...@news.freenet.de>,
=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=   wrote:
>
>In any case, I don't think you'll need a multi-process solution; a
>single-process multi-threading approach will do fine. Just create
>*another* thread, that runs at a low priority and is allowed to block.
>Run the Python interpreter in that thread (create multiple of these if
>you need them).  Then, use some queuing producer-consumer communication
>between the high-priority thread and the low priority thread. Have the
>high priority threads put requests into the queue, and the low priority
>thread take them from the queue, dispatching them to Python. Make sure
>you use non-blocking synchronization on the queue, or else priority
>inheritance if you can get permission to do so.

This is close to what I would recommend, but I would suggest that the
low-priority thread make calls out to an external Python process; that
way, you can have a Python worker pool of processes.  Based on what I've
seen posted over the years, I generally recommend against instantiating
multiple interpreter instances (although I've seen some success stories,
I've seen more people butting their heads against the brick wall).
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

The best way to get information on Usenet is not to ask a question, but
to post the wrong information.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string payload expected: error

2009-11-29 Thread Lie Ryan

On 11/27/2009 8:43 PM, Ramdas wrote:

I tried with MIMEBASE but it still fails.. I changed it to
MIMEText, hoping that might trick __handletext to think its a string
Anyway that also doesn't work.



just pass the string directly to MIMEBase.set_payload:

fp = open('...')
msg1 = MIMEBase(maintype, subtype)
msg1.set_payload(fp.read())

either that or use a more specialized subclass of MIMEBase (e.g. MIMEText).
--
http://mail.python.org/mailman/listinfo/python-list


Re: python setup.py build 32-bits on x86_64 machine

2009-11-29 Thread Aahz
In article <4b08d6e9$0$28097$a729d...@news.telepac.pt>,
=?UTF-8?B?U8Opcmdpbw==?= Monteiro Basto   wrote:
>
>I am in x86_64 arch , but I need 
>compile things on 32 bits.
>python setup.py build

Googling for "linux force 32-bit build" and similar phrases should find
some useful results.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

The best way to get information on Usenet is not to ask a question, but
to post the wrong information.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: * for generic unpacking and not just for arguments?

2009-11-29 Thread Mel
Russell Warren wrote:

> Maybe it's just that * is strictly for arguments, and trying it for
> generic tuple unpacking is abuse (which is down the corridor in 12A).

I'd agree with that.  It's a feature of function calls, not a feature of 
sequence types, so that you can handle a set of function arguments as a 
bunch, and apply them when you want.

The other function call feature that sequence types don't do is

a, b, c = **{'b':3, 'c':a, 'a':c}


Mel.


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


Re: Feature request: String-inferred names

2009-11-29 Thread David Robinow
On Sun, Nov 29, 2009 at 6:58 AM, inhahe  wrote:
> Did you say you were using gmail to post?  I think mailing lists tend to
> have issues with gmail because it puts html in the message or something like
> that.  Btw I recently set up this mailing list to send me a message back
> when I successfully posted something.  oddly enough, i only remember getting
> one such message, so maybe none of my other messages got through. :P
> i think there's a way to disable html when sending a gmail message, but
> don't quote me on that.
 I wasn't aware it was possible to Enable html but apparently it is.
Let me know if you see any html in this post.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Number of distinct substrings of a string [continuation]

2009-11-29 Thread inhahe
On Sun, Nov 29, 2009 at 9:10 AM, n00m  wrote:

>
> Even if Py by 4x *slower* -- it's still a perfect Ok for it (C# will
> be
> much (much) slower than Python).
>
>
How do you figure? As far as I know C# is many, many times faster than
Python.  (i was disappointed to find out that even IronPython is dozens of
times slower than other .net langs)
-- 
http://mail.python.org/mailman/listinfo/python-list


* for generic unpacking and not just for arguments?

2009-11-29 Thread Russell Warren
Is there a reason that this is fine:

>>> def f(a,b,c):
...   return a+b+c
...
>>> f(1, *(2,3))
6

but the code below is not?

>>> x = (3, 4)
>>> (1, 2, *x) == (1, 2, 3, 4)
Traceback (most recent call last):
  File "", line 1, in 
invalid syntax: , line 1, pos 8

Why does it only work when unpacking arguments for a function?  Is it
because the code below is preferred, and more readable?

>>> x = (3, 4)
>>> (1, 2) + x == (1, 2, 3, 4)
True

I've rooted around to see if there is an answer already and found some
threads going way back to 1998 (!!), but can't find a concise answer
as to why it is limited to args.

I don't have a burning desire for this to work, but I just tried it
unsuccessfully when building up a tuple and was mildly surprised that
it didn't work, so I'm curious why.

Maybe it's just that * is strictly for arguments, and trying it for
generic tuple unpacking is abuse (which is down the corridor in 12A).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Number of distinct substrings of a string [continuation]

2009-11-29 Thread n00m
http://en.wikipedia.org/wiki/Suffix_tree

Looks not very friendly appealing :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Number of distinct substrings of a string [continuation]

2009-11-29 Thread n00m
On Nov 29, 3:15 pm, Bearophile  wrote:
> Maybe in your C++ code there's something that can be improved, this is
> a 1:1 translation to D (V.1) language (using dlibs) and it's about 2.2
> times faster than the Psyco version:http://codepad.org/MQLj0ydB
> Using a smarter usage of memory (that is avoiding all or most memory
> allocations inside all loops), the performance difference will surely
> grow.

Very interesting. Thanks.
D code looks pretty neat. Btw D lang is among accepted langs there.
Even if Py by 4x *slower* -- it's still a perfect Ok for it (C# will
be
much (much) slower than Python).

Micro-optimizations.
Of course, the best optimization would be to implement Suffix Tree:
http://en.wikipedia.org/wiki/Trie
Currently I hardly understand/know/read/etc its core idea. My algo is
plainly stupid as soldier muddy boots.

My C++ code:


#include 
#include 
//#include 
//#include 
//#include 
#include 
#include 
#include 
#include 
using namespace std;

int main() {
clock_t start_time = clock();
freopen("88.txt", "rt", stdin);
freopen("99.txt", "wt", stdout);

int tcs;
string s;
cin >> tcs;
while (tcs-- > 0) {
cin >> s;
int n = s.size();
s = s + ' ';
vector< vector > a(128);
int ans = 0;
for (int i = n - 1; i >= 0; --i) {
int lev = 0;
for (int st = (int)a[s[i]].size() - 1; st >= 0; --st) {
int j = a[s[i]][st];
if (n - j <= lev) break;
if (s[j + lev] != s[i + lev]) continue;
if (s[j + lev / 2] != s[i + lev / 2]) continue;
int k = 0;
while (s[j + k] == s[i + k]) ++k;
if (k > lev) lev = k;
}
a[s[i]].push_back(i);
ans += n - i - lev;
}
cout << ans << endl;
}

cout << (clock() - start_time) / CLOCKS_PER_SEC << endl;

return 0;
}








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


Re: mysqldb cursor returning type along with result ?

2009-11-29 Thread Tim Chase

((Decimal("101.10"),), (Decimal("99.32"),), (Decimal("97.95"),),
(Decimal("98.45"),), (Decimal("97.39"),), (Decimal("97.91"),), (Decimal
("98.08"),), (Decimal("97.73"),))

as such :
  sum(result)
fails with "TypeError: unsupported operand type(s) for +: 'int' and
'tuple'"

How do I either get the resultset back as 'float' or convert the
returned tuple to 'floats'.?


Well, what you have is a tuple-of-tuples-of-decimals, and Sum can 
handle Decimal types just fine.  You simply have to extract the 
first (only) item in each row:


  sum(row[0] for row in result)

or

  sum(value for (value,) in result)

whichever makes more sense to you.

-tkc



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


staticmethod not callable? (trying to make a Singleton metaclass..)

2009-11-29 Thread inhahe
I'm trying to come up with a system for singletons, where I don't have to
modify anything for an individual class except to define __metaclass__ or,
if possible, to inherit another class.

I want it to raise an error if making a duplicate instance of a class is
attempted, rather than to return the same object, because my philosophy is
that if your class is a singleton and you're trying to make another instance
of it then you're doing it wrong and you should probably know.  Although the
way I'm trying to do it could apply to either philosophy.

I've seen several solutions for singletons in Python, but I don't like them,
either because they require modification to each individual singleton class,
or they require something after the class definition like Class = Class(),
or I totally don't understand them.  The novel way I've attempted to come up
with is this:

class Singleton(type):
  def __new__(meta, classname, bases, classDict):
@staticmethod
def nonewinst(*args, **kwargs):
  raise ValueError("Can't make duplicate instance of singleton " +
classname)
@staticmethod
def newoldnew(obj):
  return obj
oldnew = classDict.get("__new__", newoldnew)
@staticmethod
def newnew(obj, *args, **kwargs):
  o = oldnew(obj, *args, **kwargs)
  obj.__new__ = nonewinst
  return o
classDict["__new__"] = newnew
return type.__new__(meta, classname, bases, classDict)

a little bit of experimentation revealed that apparently even functions
defined within a method become class methods, so i tried making them all
static methods.  however, python is strange to me when it comes to methods
and the self parameter.  i mean i understand a function being free of the
class so that the 'self' parameter doesn't mean anything in particular
unless you explicitly pass it an instance.  and i understand the method
being bound to an object so that when it's called its self parameter is
automatically sent the instance.  but python seems to have this in-between
mode where sometimes a function isn't particularly bound to an instance but
if you try to pass the wrong kind of instance to 'self' it'll complain,
which gets annoying, and i don't understand how its binding works. but
anyway, the problem i'm currently having with the code might not even be
related to that..because here's the error I'm getting:

>>> from funcs import Singleton
>>> class A:
...   __metaclass__ = Singleton
...
>>> b = A()
Traceback (most recent call last):
  File "", line 1, in 
  File "c:\python25\funcs.py", line 68, in newnew
o = oldnew(obj, *args, **kwargs)
TypeError: 'staticmethod' object is not callable

i'm not that experienced with metaclasses, but it seems to me that
something's obviously going fubar here because at that point oldnew should
be the function newoldnew (since class A doesn't have a __new__ defined)
which is clearly defined right there with a staticmethod decorator, and
first of all, functions *should* be callable, and secondly, why is my object
a 'staticmethod' object just because I used a decorator on it?  it would
seem it should be a function, so i tested it like this:

>>> class A:
...   @staticmethod
...   def b(): pass
...
>>> type(A.b)


in that case, using @staticmethod returns a function.  i have nfi why it's
different in my Singleton class.

oh, and thirdly, staticmethod is a decorator and decorators are callables so
even given that for some mysterious reason it's a staticmethod object i
don't know why it's not callable.  so that's pretty confusing.  can anyone
clear this up for me?  thanks..

ps. i'm aware of the evils of singletons and all that.  short answer: I
don't care.  :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Number of distinct substrings of a string [continuation]

2009-11-29 Thread Bearophile
n00m:
> my home tests proved Python is a fellow fast beast of C++.
> Quite unexpected (I expected Py would be by ~10 times slower).
> PS
> Both my codes are identical in their algorithms.

> =
> 0.016         0.0150001049042   <--- exec times

Maybe in your C++ code there's something that can be improved, this is
a 1:1 translation to D (V.1) language (using dlibs) and it's about 2.2
times faster than the Psyco version:
http://codepad.org/MQLj0ydB
Using a smarter usage of memory (that is avoiding all or most memory
allocations inside all loops), the performance difference will surely
grow.

Bye,
bearophile
-- 
http://mail.python.org/mailman/listinfo/python-list


mysqldb cursor returning type along with result ?

2009-11-29 Thread Paul O'Sullivan
Just taken to Python (2.5)and started to look at some DB cursor stuff
using MySQL.  Anyway, after creating a query that in MySQL that has a
result set of decimals I find that the cursor in python after a
fetchall() returns a tuple that contains the following ::

((Decimal("101.10"),), (Decimal("99.32"),), (Decimal("97.95"),),
(Decimal("98.45"),), (Decimal("97.39"),), (Decimal("97.91"),), (Decimal
("98.08"),), (Decimal("97.73"),))

as such :
  sum(result)
fails with "TypeError: unsupported operand type(s) for +: 'int' and
'tuple'"

How do I either get the resultset back as 'float' or convert the
returned tuple to 'floats'.?

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


Re: Number of distinct substrings of a string [continuation]

2009-11-29 Thread Bearophile
n00m:
> My Py solution:
> ...

Cute. You can replace:
a[ord(s[i])] += [i]
With:
a[ord(s[i])].append(i)

If you want to micro-optimize this with Psyco may be a little faster:
(lev >> 1)
Than:
lev // 2

But to increase speed it's usually better to reduce memory
allocations. So you can try to find a way to pull this out of the
function:
a = [[] for i in xrange(128)]
And to avoid a true append:
a[ord(s[i])] += [i]

(There are many ways to avoid an append. One of them is to have an
already allocated list/array and just bump forward an index variable
that starts from 0. This is worth doing especially when you use
Psyco).

Bye,
bearophile
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >