Re: Python IDE/Eclipse

2011-08-28 Thread flebber
On Aug 27, 6:34 pm, UncleLaz  wrote:
> On Aug 26, 5:18 pm, Dave Boland  wrote:
>
>
>
>
>
>
>
>
>
> > I'm looking for a good IDE -- easy to setup, easy to use -- for Python.
> >   Any suggestions?
>
> > I use Eclipse for other projects and have no problem with using it for
> > Python, except that I can't get PyDev to install.  It takes forever,
> > then produces an error that makes no sense.
>
> > An error occurred while installing the items
> >    session context was:(profile=PlatformProfile,
> > phase=org.eclipse.equinox.internal.provisional.p2.engine.phases.Install,
> > operand=null --> [R]org.eclipse.cvs 1.0.400.v201002111343,
> > action=org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.InstallBu 
> > ndleAction).
> >    Cannot connect to keystore.
> >    This trust engine is read only.
> >    The artifact file for
> > osgi.bundle,org.eclipse.cvs,1.0.400.v201002111343 was not found.
>
> > Any suggestions on getting this to work?
>
> > Thanks,
> > Dave
>
> I use Aptana Studio 3, it's pretty good and it's based on eclipse

Emacs with emacs-for-python makes the install and setup a breeze and
emacs does a lot for you without much learning.
http://gabrielelanaro.github.com/emacs-for-python/

geany is great I use it the most.
http://www.geany.org/

Finally this is a fairly new project, but it could be pretty good.
they are heavy in development of version 2. Ninja ide
http://ninja-ide.org/
they provide packages for Debian/ubuntu fedora mandriva & windows and
the developers are very helpful if you have any issues or questions
jump on IRC for a chat.

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


On re / regex replacement

2011-08-28 Thread jmfauth
There is actually a discussion on the dev-list about the replacement
of "re" by "regex".

I'm not a regular expressions specialist, neither a regex user.
However, there is in regex a point that is a little bit disturbing
me.

The regex module proposes a flag to select the "coding" (wrong word,
just to be short):

The global flags are: ASCII, LOCALE, NEW, REVERSE, UNICODE.

If I can undestand the ASCII flag, ASCII being the "lingua franca" of
almost all codings, I am more skeptical about the LOCALE/UNICODE
flags.

There is in my mind some kind of conflict here. What is 100% unicode
compliant shoud be locale independent ("Unicode.org") and a locale
depedency means a loss of unicode compliance.

I'm fearing some potential problems here:  Users or modules working
in one mode, while some others are working in the other mode.

Nothing technical here. It seems to me nobody has pointed this
fact.

jmf

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


Re: Record seperator

2011-08-28 Thread greymaus
On 2011-08-27, Steven D'Aprano  wrote:
> greymaus wrote:
>
>> On 2011-08-26, D'Arcy J.M. Cain  wrote:
>>> On 26 Aug 2011 18:39:07 GMT
>>> greymaus  wrote:
 
 Is there an equivelent for the AWK RS in Python?
 
 
 as in RS='\n\n'
 will seperate a file at two blank line intervals
>>>
>>> open("file.txt").read().split("\n\n")
>>>
>> 
>> 
>> Ta!.. bit awkard. :))
>
> Er, is that meant to be a pun? "Awk[w]ard", as in awk-ward?

Yup, mispelled it and realized th error :)
>
> In any case, no, the Python line might be a handful of characters longer
> than the AWK equivalent, but it isn't awkward. It is logical and easy to
> understand. It's embarrassingly easy to describe what it does:
>
> open("file.txt")   # opens the file
>  .read()   # reads the contents of the file
>  .split("\n\n")# splits the text on double-newlines.
>
> The only tricky part is knowing that \n means newline, but anyone familiar
> with C, Perl, AWK etc. should know that.
>
> The Python code might be "long" (but only by the standards of AWK, which can
> be painfully concise), but it is simple, obvious and readable. A few extra
> characters is the price you pay for making your language readable. At the
> cost of a few extra key presses, you get something that you will be able to
> understand in 10 years time.
>
> AWK is a specialist text processing language. Python is a general scripting
> and programming language. They have different values: AWK values short,
> concise code, Python is willing to pay a little more in source code.
>
>

RS, and its Perl equivelent, which I forget, mean that you can read in
full multiline records. 

(I am coming into Python via Perl from AWK, and trying to get a grip
on the language and its idions)

Thanks to All

Oh, Awk is far more than a text processing language, may be old (like me!)
but useful (ditto)



-- 
maus
 .
  .
...   NO CARRIER
-- 
http://mail.python.org/mailman/listinfo/python-list


inpipe and outpipe (and other useful functions)

2011-08-28 Thread Ole Martin Bjørndalen
Hi!

Please excuse me if this i common knowledge, or if I've one again
re-implemented something
that turned out to be in the standard library, but I think I came up
with something rather neat.

I'm writing a lot of programs that call external programs, and as much
as I love subproces.Popen, I do get tired of writing
rather wordy things like:

   args = ['cmd', 'arg1', 'arg2', 'etc']
   p = subprocess.Popen(args, stdin=subprocess.PIPE)
   for line in p:
  line = line.decode('latin1')
  do_something_with(line)

Bleh.

so last week I had enough, and I sat down and wrote a few functions.
No I can do:

from lib import inpipe

for line in inpipe(args, encoding='latin1'):
do_something_with(line)

and

from lib import outpipe

with outpipe(args, addnl=True) as write:
write('Python is awesome!')
write('')

Some code from a program I'm writing:

args = ['metaflac',
   '--show-total-samples',
   '--show-sample-rate',
   file]

for line in stripped(inpipe(args)):
(name, value) = line.split('=')
# ... process tag

Now, that is a lot more readable than what I had before!

The library has a lot of other things in it as well, and is available here:

https://github.com/olemb/lib

I love Python!


-- 
Ole Martin,
http://nerdly.info/ole/
-- 
http://mail.python.org/mailman/listinfo/python-list


pyzmail-0.9.0: high level mail library to read, write and send emails easily

2011-08-28 Thread aspineux
Python easy mail library

pyzmail is a high level mail library for Python. It provides functions
and classes that help to read, compose and send emails. pyzmail exists
because their is no reasons that handling mails with Python would be
more difficult than with popular mail clients like Outlook or
Thunderbird. pyzmail hide the difficulties of the MIME structure and
MIME encoding/decoding. It also hide the problem of the
internationalized header encoding/decoding.

More here http://www.magiksys.net/pyzmail/

You can get a lot of usage samples from the inside API documentation :
http://www.magiksys.net/pyzmail/api/index.html

This library is the result of 3 articles I wrote about sending mail
using python

- Parsing email using Python part 1 of 2 : The Header
http://blog.magiksys.net/parsing-email-using-python-header
- Parsing email using Python part 2 of 2 : The content
http://blog.magiksys.net/parsing-email-using-python-content
- Generate and send mail with python: tutorial
http://blog.magiksys.net/generate-and-send-mail-with-python-tutorial

pyzmail also include a very nice "pyzsendmail" command line utility
to send the most complex email from the command line.

"pyzsendmail -h" for more


I'm waiting for your feedback
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python IDE/Eclipse

2011-08-28 Thread Alec Taylor
Editra

On Sun, Aug 28, 2011 at 5:56 PM, flebber  wrote:
> On Aug 27, 6:34 pm, UncleLaz  wrote:
>> On Aug 26, 5:18 pm, Dave Boland  wrote:
>>
>>
>>
>>
>>
>>
>>
>>
>>
>> > I'm looking for a good IDE -- easy to setup, easy to use -- for Python.
>> >   Any suggestions?
>>
>> > I use Eclipse for other projects and have no problem with using it for
>> > Python, except that I can't get PyDev to install.  It takes forever,
>> > then produces an error that makes no sense.
>>
>> > An error occurred while installing the items
>> >    session context was:(profile=PlatformProfile,
>> > phase=org.eclipse.equinox.internal.provisional.p2.engine.phases.Install,
>> > operand=null --> [R]org.eclipse.cvs 1.0.400.v201002111343,
>> > action=org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.InstallBu
>> >  ndleAction).
>> >    Cannot connect to keystore.
>> >    This trust engine is read only.
>> >    The artifact file for
>> > osgi.bundle,org.eclipse.cvs,1.0.400.v201002111343 was not found.
>>
>> > Any suggestions on getting this to work?
>>
>> > Thanks,
>> > Dave
>>
>> I use Aptana Studio 3, it's pretty good and it's based on eclipse
>
> Emacs with emacs-for-python makes the install and setup a breeze and
> emacs does a lot for you without much learning.
> http://gabrielelanaro.github.com/emacs-for-python/
>
> geany is great I use it the most.
> http://www.geany.org/
>
> Finally this is a fairly new project, but it could be pretty good.
> they are heavy in development of version 2. Ninja ide
> http://ninja-ide.org/
> they provide packages for Debian/ubuntu fedora mandriva & windows and
> the developers are very helpful if you have any issues or questions
> jump on IRC for a chat.
>
> Sayth
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: On re / regex replacement

2011-08-28 Thread Vlastimil Brom
2011/8/28 jmfauth :
> There is actually a discussion on the dev-list about the replacement
> of "re" by "regex".
>...
> If I can undestand the ASCII flag, ASCII being the "lingua franca" of
> almost all codings, I am more skeptical about the LOCALE/UNICODE
> flags.
>
> There is in my mind some kind of conflict here. What is 100% unicode
> compliant shoud be locale independent ("Unicode.org") and a locale
> depedency means a loss of unicode compliance.
>
> I'm fearing some potential problems here:  Users or modules working
> in one mode, while some others are working in the other mode.
>
>...
> jmf
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


As I understand it, regex was designed to be as much compatible with
re as possible, sometimes even some problematic (in some
interpretation) behaviour is retained as default and "corrected" via
the NEW flag (e.g. zero-width split). Also the LOCALE flag seems to be
considered as legacy feature and kept with the same behaviour like re;
cf.: http://code.google.com/p/mrab-regex-hg/issues/detail?id=6&can=1
In my opinon, the LOCALE flag is not reliable (in a way I would
imagine) in either re or regex.

In the area of flags regex should work the same way like re or it just
adds more possibilities (REVERSE for backwards search,  ASCII as the
complement for unicode, NEW to enable some incompatible additions or
corrections, where the original behaviour could be relied on).

The only (understandable) incompatibility I encounter in regex are the
new features requiring special syntax, which would obviously raise
errors in re or which would be matched literally instead.
see
http://code.google.com/p/mrab-regex-hg/wiki/GeneralDetails#Additional_features
for an overview of the additions.

Personally I am very happy with regex, both with its features as well
as with the support and maintenance by its developer;
however I am mostly using it for manually entered patterns, and less
for hardcoded operation.

regards,
   Vlastimil Brom
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why do closures do this?

2011-08-28 Thread Thomas Jollans
On 28/08/11 05:45, John O'Hagan wrote:
> Somewhat apropos of the recent "function principle" thread, I was recently 
> surprised by this:
> 
> funcs=[]
> for n in range(3):
> def f():
> return n
> funcs.append(f)
> 
> [i() for i in funcs]
> 
> The last expression, IMO surprisingly, is [2,2,2], not [0,1,2]. Google tells 
> me I'm not the only one surprised, but explains that it's because "n" in the 
> function "f" refers to whatever "n" is currently bound to, not what it was 
> bound to at definition time (if I've got that right), and that there are at 
> least two ways around it: either make a factory function:


This does not do what you'd like it to do. But let's assume that, it
did, that Python, when encountering a function definition inside a
function, "froze" the values of nonlocal variables used in the new
function, from the point of view of that function — that *might* be more
intuitive, at least in certain situations. However, what if you wanted a
closure to access a nonlocal variable that changes - acting differently
depending on what has since happened in the parent function.

That may not be as common, but it is a perfectly plausible situation,
and the hack required to support that behaviour in a Python that acts as
you had expected it to, a surrogate namespace using a class, list, or
dict, is infinitely more cryptic and ugly than the default-parametre hack.

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


Re: Why do closures do this?

2011-08-28 Thread Terry Reedy

On 8/28/2011 10:04 AM, Thomas Jollans wrote:


This does not do what you'd like it to do. But let's assume that, it
did, that Python, when encountering a function definition inside a
function, "froze" the values of nonlocal variables used in the new
function, from the point of view of that function — that *might* be more
intuitive, at least in certain situations. However, what if you wanted a
closure to access a nonlocal variable that changes - acting differently
depending on what has since happened in the parent function.

That may not be as common, but it is a perfectly plausible situation,
and the hack required to support that behaviour in a Python that acts as
you had expected it to, a surrogate namespace using a class, list, or
dict, is infinitely more cryptic and ugly than the default-parametre hack.


Or, what if the nonlocal name is not even defined when the closure is.

>>> def f():
def g(): print(a)
a = 3
g()

>>> f()
3

Note that global names also do not have to be defined when a function 
using them is compiled. The current situation is that nonlocal and 
global names are treated the same way. This makes normal and nested 
functions as much the same as possible. This is intentional. It would be 
extremely disconcerting if moving code that contains a def into or out 
of a wrapping function radically changed its behavior more than is 
absolutely necessary.


--
Terry Jan Reedy


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


about if __name == '__main__':

2011-08-28 Thread Amit Jaluf
hello group

i have one question about this

if __name == '__main__':

is it same as other languages like[c,c++]  main function. because of i
google and read faqs
and also " 
http://docs.python.org/faq/programming#how-do-i-find-the-current-module-name";
this and i am confused.

thanks

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


Re: Understanding .pth files

2011-08-28 Thread Ian Kelly
On Sat, Aug 27, 2011 at 10:42 AM, Josh English
 wrote:
> According to the docs, I should be able to put a file in the site-packages 
> directory called xmldb.pth pointing anywhere else on my drive to include the 
> package. I'd like to use this to direct Python to include the version in the 
> dev folder and not the site-packages folder.

The name of the .pth file is not important.  Python uses it to add
locations to sys.path; it doesn't care what packages might be
contained at those locations.

> So my C:\Python27\lib\site-packages\xmldb.pth file has one line:
>
> c:\dev\XmlDB\xmldb

The final xmldb is the actual package, yes?  The directory in the .pth
file should be one inside which Python can find packages, not a
package itself.  So the file should have just "c:\dev\XmlDB".  Then
when you do "import xmldb", Python will look inside the
"c:\dev\XmlDB", find the xmldb package, and import it.

>
> (I've tried the slashes the other way, too, but it doesn't seem to work).
>
> Is the only solution to delete the installed library and add the dev folder 
> to my site.py file?

The preferred solution here is to use virtualenv to set up your
development environment without having to modify the installed version
in the system site-packages at all.

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


Re: about if __name == '__main__':

2011-08-28 Thread Ian Kelly
On Sun, Aug 28, 2011 at 9:34 AM, Amit Jaluf  wrote:
> hello group
>
> i have one question about this
>
> if __name == '__main__':

First, it should be:

if __name__ == '__main__':

> is it same as other languages like[c,c++]  main function. because of i
> google and read faqs
> and also " 
> http://docs.python.org/faq/programming#how-do-i-find-the-current-module-name";
> this and i am confused.

No, that is not a main function.  It's not even a function.  When
Python runs a script, it loads that script as a module, sets its name
to be __main__, and then executes the entire module, starting from the
top as normal.  What that if statement defines is an ordinary branch
that is only executed if the current module is the main module, as
opposed to having been imported from some other module.  Normally this
will be at the end of the file so that all the definitions in the file
will have already been executed.

The usual idiom for this is:

def main(argv):
# parse arguments and begin program logic...
pass

if __name__ == '__main__':
import sys
main(sys.argv)

This is also frequently used for unit testing of library modules, so
that the module can be tested just by running it.

# define library classes and functions here

if __name__ == '__main__':
# perform unit tests

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


A question about class as an iterator

2011-08-28 Thread Yaşar Arabacı
Hi,

I got confused about classes as an iterator. I saw something like this:

class foo():
__iter__(self):
return self
next(self):
return something

But then I saw a __next__ method on some code. So what is the deal, which
one should I use and what is the difference?

-- 
http://yasar.serveblog.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: On re / regex replacement

2011-08-28 Thread MRAB

On 28/08/2011 14:40, Vlastimil Brom wrote:

2011/8/28 jmfauth:

There is actually a discussion on the dev-list about the replacement
of "re" by "regex".
...
If I can undestand the ASCII flag, ASCII being the "lingua franca" of
almost all codings, I am more skeptical about the LOCALE/UNICODE
flags.

There is in my mind some kind of conflict here. What is 100% unicode
compliant shoud be locale independent ("Unicode.org") and a locale
depedency means a loss of unicode compliance.

I'm fearing some potential problems here:  Users or modules working
in one mode, while some others are working in the other mode.

...
jmf

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




As I understand it, regex was designed to be as much compatible with
re as possible, sometimes even some problematic (in some
interpretation) behaviour is retained as default and "corrected" via
the NEW flag (e.g. zero-width split). Also the LOCALE flag seems to be
considered as legacy feature and kept with the same behaviour like re;
cf.: http://code.google.com/p/mrab-regex-hg/issues/detail?id=6&can=1
In my opinon, the LOCALE flag is not reliable (in a way I would
imagine) in either re or regex.


In Python 2, re defaults to ASCII and you must use UNICODE for Unicode
strings (the str type is a bytestring). In Python 3, re defaults to
UNICODE and you must use ASCII for ASCII bytestrings (the str type is a
Unicode string).

The LOCALE flag is for locale-dependent 8-bit bytestrings. It uses the
toupper and tolower functions of the underlying C library.

The regex module tries to be drop-in compatible. It supports the LOCALE
flag only because the re module has it. Even Perl has something similar.


In the area of flags regex should work the same way like re or it just
adds more possibilities (REVERSE for backwards search,  ASCII as the
complement for unicode, NEW to enable some incompatible additions or
corrections, where the original behaviour could be relied on).

The only (understandable) incompatibility I encounter in regex are the
new features requiring special syntax, which would obviously raise
errors in re or which would be matched literally instead.
see
http://code.google.com/p/mrab-regex-hg/wiki/GeneralDetails#Additional_features
for an overview of the additions.


In the re module, unknown escape sequences are treated as literals, eg
\K is treated as K.

The regex module has more escape sequences, so that may break existing
regexes, eg \X isn't treated as X, but matches a grapheme. Unknown
escape sequences are still treated as literals, as in re.

My view is that you shouldn't be relying on that behaviour. If it looks
like an escape sequence, it may very well be one. It's like their use
in strings literals for file paths on Windows. I would've preferred
that a invalid escape sequence in a string literal raised an exception
(either it's valid and has a meaning, or it's invalid/reserved for
future use).

It's a balancing act. Requiring the NEW flag for _any_ deviation from
re would be very annoying.


Personally I am very happy with regex, both with its features as well
as with the support and maintenance by its developer;
however I am mostly using it for manually entered patterns, and less
for hardcoded operation.


And I'm very happy with your feedback. ;-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: about if __name == '__main__':

2011-08-28 Thread woooee
Two main routines, __main__ and main(), is not the usual or the common
way to do it.  It is confusing and anyone looking at the end of the
program for statements executed when the program is called will find
an isolated call to main(), and then have to search the program for
the statements that should have been at the bottom of the program.
The only reason to use such a technique in Python is if you want to
call the function if the program is run from the command line, and
also call the same function if the program is imported from another.
In which case, use a name that is descriptive, not "main".  And be
careful of anyone that gives you programming advice.  Research these
things for yourself.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Processing a large string

2011-08-28 Thread Paul Rudin
goldtech  writes:

> Hi,
>
> Say I have a very big string with a pattern like:
>
> akakksssk3dhdhdhdbddb3dkdkdkddk3dmdmdmd3dkdkdkdk3asnsn.
>
> I want to split the sting into separate parts on the "3" and process
> each part separately. I might run into memory limitations if I use
> "split" and get a big array(?)  I wondered if there's a way I could
> read (stream?) the string from start to finish and read what's
> delimited by the "3" into a variable, process the smaller string
> variable then append/build a new string with the processed data?
>
> Would I loop it and read it char by char till a "3"...? Or?
>
> Thanks.

s = "akakksssk3dhdhdhdbddb3dkdkdkddk3dmdmdmd3dkdkdkdk3asnsn"
for k, subs in itertools.groupby(s, lambda x: x=="3"):
   print ''.join(subs)


what you actually do in the body of the loop depends on what you want to
do with the bits.
-- 
http://mail.python.org/mailman/listinfo/python-list


Fwd: Processing a large string

2011-08-28 Thread Yaşar Arabacı
-- Yönlendirilmiş ileti --
Kimden: Yaşar Arabacı 
Tarih: 28 Ağustos 2011 22:51
Konu: Re: Processing a large string
Kime: Paul Rudin 


Are you getting Overflow error or memory error? If you don't know what those
means:

Overflow error occurs when your lists gets bigger than sys.maxsize in size.
Memory error occurs, when your objects take too much memory that no more
memory can be allocated for you.

For example, if you have only one item in your list, and that item consumes
all your memory, you will get memory error. On the other hand, if you put so
much items to the list that list index hits the sys.maxsize value, you will
get Overflow error.

Answer to your questions depends on spesifics of your needs and current
situation. If you can read whole of the string without getting memory error,
you wont get memory error when you split the string into a list (at least in
my theory), but you can still get Overflowerror (in 2.6 at least.). If your
string is in a file or buffer, I would do something like,

file__ = open("big-string.txt","r")
output__ = open("outputfile","w")

temp__ = ""

def process_string(string_):
return processed_string

while 1:
new_char = file.read(1)
if new_char == "":
break
elif new_char == "3":
output__.write(process_string(temp__))
temp__ = ""
else:
temp__ = temp__ + new_char


2011/8/28 Paul Rudin 

> goldtech  writes:
>
> > Hi,
> >
> > Say I have a very big string with a pattern like:
> >
> > akakksssk3dhdhdhdbddb3dkdkdkddk3dmdmdmd3dkdkdkdk3asnsn.
> >
> > I want to split the sting into separate parts on the "3" and process
> > each part separately. I might run into memory limitations if I use
> > "split" and get a big array(?)  I wondered if there's a way I could
> > read (stream?) the string from start to finish and read what's
> > delimited by the "3" into a variable, process the smaller string
> > variable then append/build a new string with the processed data?
> >
> > Would I loop it and read it char by char till a "3"...? Or?
> >
> > Thanks.
>
> s = "akakksssk3dhdhdhdbddb3dkdkdkddk3dmdmdmd3dkdkdkdk3asnsn"
> for k, subs in itertools.groupby(s, lambda x: x=="3"):
>   print ''.join(subs)
>
>
> what you actually do in the body of the loop depends on what you want to
> do with the bits.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://yasar.serveblog.net/




-- 
http://yasar.serveblog.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why do closures do this?

2011-08-28 Thread Carl Banks
On Saturday, August 27, 2011 8:45:05 PM UTC-7, John O'Hagan wrote:
> Somewhat apropos of the recent "function principle" thread, I was recently 
> surprised by this:
> 
> funcs=[]
> for n in range(3):
> def f():
> return n
> funcs.append(f)
> 
> [i() for i in funcs]
> 
> The last expression, IMO surprisingly, is [2,2,2], not [0,1,2]. Google tells 
> me I'm not the only one surprised, but explains that it's because "n" in the 
> function "f" refers to whatever "n" is currently bound to, not what it was 
> bound to at definition time (if I've got that right), and that there are at 
> least two ways around it: 
> My question is, is this an inescapable consequence of using closures, or is 
> it by design, and if so, what are some examples of where this would be the 
> preferred behaviour?


It is the preferred behavior for the following case.

def foo():
def printlocals():
print a,b,c,d
a = 1; b = 4; c = 5; d = 0.1
printlocals()
a = 2
printlocals()

When seeing a nested function, there are strong expectations by most people 
that it will behave this way (not to mention it's a lot more useful).  It's 
only for the less common and much more advanced case of creating a closure in a 
loop that the other behavior would be preferred.


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


Checking Signature of Function Parameter

2011-08-28 Thread Travis Parks
I am trying to write an algorithms library in Python. Most of the
functions will accept functions as parameters. For instance, there is
a function called any:

def any(source, predicate):
for item in source:
if predicate(item):
return true;
return false;

There are some things I want to make sure of. 1) I want to make sure
that source is iterable. 2) More importantly, I want to make sure that
predicate is callable, accepting a thing, returning a bool.

This is what I have so far:

if source is None: raise ValueError("")
if not isinstanceof(source, collections.iterable): raise TypeError("")
if not callable(predicate): raise TypeError("")

The idea here is to check for issues up front. In some of the
algorithms, I will be using iterators, so bad arguments might not
result in a runtime error until long after the calls are made. For
instance, I might implement a filter method like this:

def where(source, predicate):
for item in source:
if predicate(item):
yield item

Here, an error will be delayed until the first item is pulled from the
source. Of course, I realize that functions don't really have return
types. Good thing is that virtually everything evaluates to a boolean.
I am more concerned with the number of parameters.

Finally, can I use decorators to automatically perform these checks,
instead of hogging the top of all my methods?

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


Re: A question about class as an iterator

2011-08-28 Thread Terry Reedy

On 8/28/2011 1:22 PM, Yaşar Arabacı wrote:


I got confused about classes as an iterator. I saw something like this:

class foo():
 __iter__(self):
 return self
 next(self):
 return something


2.x


But then I saw a __next__ method on some code.


3.x
This might work in 2.6 or .7, but I do not really know.

The next() builting was introduced in 2.6 so that *users* could write
item = next(someiter)
and have that work in 2.6+ and in 3.x without change.


which one should I use?


Depends on your Python version. I recommend you use 3.2 unless you have 
a reason or need to use something else.


--
Terry Jan Reedy


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


Re: Checking Signature of Function Parameter

2011-08-28 Thread Chris Angelico
On Mon, Aug 29, 2011 at 7:20 AM, Travis Parks  wrote:
>
> if source is None: raise ValueError("")
> if not isinstanceof(source, collections.iterable): raise TypeError("")
> if not callable(predicate): raise TypeError("")
>

Easier: Just ignore the possibilities of failure and carry on with
your code. If the source isn't iterable, you'll get an error raised by
the for loop. If the predicate's not callable, you'll get an error
raised when you try to call it. The only consideration you might need
to deal with is that the predicate's not callable, and only if you're
worried that consuming something from your source would be a problem
(which it won't be with the normal iterables - strings, lists, etc,
etc). Otherwise, just let the exceptions be raised!

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


Re: about if __name == '__main__':

2011-08-28 Thread Terry Reedy

On 8/28/2011 2:56 PM, woooee wrote:

Two main routines, __main__ and main(),


'__main__' in not a routine, it is the name of the initial module.


is not the usual or the common
way to do it.  It is confusing and anyone looking at the end of the
program for statements executed when the program is called will find
an isolated call to main(), and then have to search the program for
the statements that should have been at the bottom of the program.
The only reason to use such a technique in Python is if you want to
call the function if the program is run from the command line, and
also call the same function if the program is imported from another.
In which case, use a name that is descriptive, not "main".  And be
careful of anyone that gives you programming advice.  Research these
things for yourself.


As far as I know, all the Lib/test/test_xxx.py file have a test_main 
function, so one can write (in IDLE, for instance)

from test.test_xxx import test_main as f; f()
and run that test. Very handy.

--
Terry Jan Reedy

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


Re: Why PyImport_ExecCodeModule takes char*?

2011-08-28 Thread Tim Roberts
Mateusz Loskot  wrote:
>
>I'm wondering, why PyImport_ExecCodeModule function takes char*
>instead of const char*?

My guess is "history".
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: about if __name == '__main__':

2011-08-28 Thread Ian Kelly
On Sun, Aug 28, 2011 at 12:56 PM, woooee  wrote:
> Two main routines, __main__ and main(), is not the usual or the common
> way to do it.  It is confusing and anyone looking at the end of the
> program for statements executed when the program is called will find
> an isolated call to main(), and then have to search the program for
> the statements that should have been at the bottom of the program.

Not a problem if you write them one after another.  Besides which, any
decent editor will have a command to go directly from the function
call to the function definition, so I really don't see this as a
problem.

> The only reason to use such a technique in Python is if you want to
> call the function if the program is run from the command line, and
> also call the same function if the program is imported from another.

Or if your main "routine" has variables, and you don't particularly
want them polluting the module's global namespace.

> In which case, use a name that is descriptive, not "main".

"main" is descriptive in that it clearly designates the entry point of
the script to anybody accustomed to such terminology.  But there is
certainly no reason it needs to be "main", and in fact I only used
that for the example.  In an actual script I would use whatever seems
appropriate.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: about if __name == '__main__':

2011-08-28 Thread Cameron Simpson
On 28Aug2011 11:56, woooee  wrote:
| Two main routines, __main__ and main(), is not the usual or the common
| way to do it.  It is confusing and anyone looking at the end of the
| program for statements executed when the program is called will find
| an isolated call to main(), and then have to search the program for
| the statements that should have been at the bottom of the program.

Firstly, as Terry remarked, __main__ is a name, not a function.

Secondly, "search the program for the statements that should have been at the
bottom of the program" isn't how I see it. If I have a module I expect
to be usable from the command line easily it looks like this:

  def main(argv):
... command line program logic ...
return exit_code

  ... all the other module contents ...

  if __name__ == '__main__':
import sys
sys.exit(main(sys.argv))

That way the top level command line program logic is at the top of the file
where it is easy to find, not buried in the middle or at the bottom.

Cheers,
-- 
Cameron Simpson  DoD#743
http://www.cskk.ezoshosting.com/cs/

Anarchy is not lack of order. Anarchy is lack of ORDERS.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why PyImport_ExecCodeModule takes char*?

2011-08-28 Thread Terry Reedy

On 8/28/2011 6:52 PM, Tim Roberts wrote:

Mateusz Loskot  wrote:


I'm wondering, why PyImport_ExecCodeModule function takes char*
instead of const char*?


My guess is "history".


I believe some const tags have been added over the last few years. 
Another factory than mere history for some things is portability across 
platforms and the main compilers.


--
Terry Jan Reedy

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


Unpickle error -- "object has no attribute ...."

2011-08-28 Thread luvspython
I have an application that needs to keep a history of the values of
several attributes of each of many instances of many classes.  The
history-keeping logic is in a helper class, HistoryKeeper, that's
inherited by classes like Vehicle in the example below.

Pickling an instance of Vehicle works, but unpickling fails with:
 "Vehicle object has no attribute
'_orderedArgNames'"   (_orderedArgNames is an attribute in
HistoryKeeper that tells the attributes for which history must be
kept.)

During unpickling, the exception occurs at the 2nd line in the
__getattribute__ method:
if item not in object.__getattribute__(self,
'_orderedArgNames'):

FWIW, cPickle fails the same way.

Below is a stripped-down example that fails in unpickling.

Can anyone explain why it fails and what I can do to fix it?

MANY thanks.

=

import datetime, bisect
from collections import OrderedDict



# define a class which helps keep date-history of attribute settings
in inheriting classes
class HistoryKeeper(object):
""" Class to maintain a dated history of attribute settings in
inheriting classes.
The initialization arguments are in an OrderedDict."""
def __init__(self, orderedArgs):
super(HistoryKeeper, self).__setattr__('_orderedArgNames',
orderedArgs.keys())   #remember the order of unnamed args
for arg, value in orderedArgs.items():
if arg != 'self':
self.Set(arg, value)


""" Get the current value of an attribute, optionally returning
its entire history."""
def __getattribute__(self, item, returnHistory=False):
value = object.__getattribute__(self, item)
if item not in object.__getattribute__(self,
'_orderedArgNames'):
return value # not an attribute for which we
maintain a change history
elif returnHistory:
return value # return the entire history
else:
return value[-1][0]  # return only the latest
value


""" Set an attribute by appending the new value and date to
existing history of that attribute.
Unless a setting-date is supplied, default to today.
Set the value only if it's different than the chronological
immediately preceding value."""
def __setattr__(self, item, value, date=None):

# avoid history keeping if this item isn't among those
declared to require it
if item not in self._orderedArgNames:
super(HistoryKeeper, self).__setattr__(item, value)
else:
if not date:
date = datetime.date.today()
# if this attribute has already been set, add this value
to that history
try:
history = self.__getattribute__(item,
returnHistory=True)
# if a date was supplied, ensure the history remains
in chronological order
dates = [val[1] for val in history]
index = bisect.bisect_right(dates, date)
# insert this value into the history unless it doesn't
change an existing setting
if index == 0 or history[index-1][0] != value:
history.insert(index, (value,date))
except:
history = [(value, date)]
super(HistoryKeeper, self).__setattr__(item, history)

def Set(self, item, value):
self.__setattr__(item, value)




class Vehicle(HistoryKeeper):
def __init__(self, tag, make, model):
argDict = OrderedDict([('tag',tag),('make',make),
('model',model)])
super(Vehicle, self).__init__(argDict)

if __name__ == "__main__":
car = Vehicle('TAG123', 'FORD', 'Model A')

import pickle
pFile = open('car.pk1', 'wb')
pickle.dump(car, pFile, -1)
pFile.close()
print "car pickled OK"

pFile = open('car.pk1', 'rb')
community = pickle.load(pFile)
pFile.close()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Checking Signature of Function Parameter

2011-08-28 Thread Travis Parks
On Aug 28, 5:31 pm, Chris Angelico  wrote:
> On Mon, Aug 29, 2011 at 7:20 AM, Travis Parks  wrote:
>
> > if source is None: raise ValueError("")
> > if not isinstanceof(source, collections.iterable): raise TypeError("")
> > if not callable(predicate): raise TypeError("")
>
> Easier: Just ignore the possibilities of failure and carry on with
> your code. If the source isn't iterable, you'll get an error raised by
> the for loop. If the predicate's not callable, you'll get an error
> raised when you try to call it. The only consideration you might need
> to deal with is that the predicate's not callable, and only if you're
> worried that consuming something from your source would be a problem
> (which it won't be with the normal iterables - strings, lists, etc,
> etc). Otherwise, just let the exceptions be raised!
>
> ChrisA

I guess my concern is mostly with the delayed exceptions. It is hard
to find the source of an error when it doesn't happen immediately. I
am writing this library so all of the calls can be chained together
(composed). If this nesting gets really deep, finding the source is
hard to do, even with a good debugger.

Maybe I should give up on it, like you said. I am still familiarizing
myself with the paradigm. I want to make sure I am developing code
that is consistent with the industry standards.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Checking Signature of Function Parameter

2011-08-28 Thread Chris Angelico
On Mon, Aug 29, 2011 at 10:20 AM, Travis Parks  wrote:
> Maybe I should give up on it, like you said. I am still familiarizing
> myself with the paradigm. I want to make sure I am developing code
> that is consistent with the industry standards.
>

In Python, the industry standard is "easier to ask forgiveness than
permission" - that is, let the exceptions happen. It's not worth the
hassle of error-checking when the result of not checking an error is
exactly the same thing.

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


Why I need the parameter when the call doesn't use it?

2011-08-28 Thread Niklas Rosencrantz
I modularize code for a webapp and I want to know what python makes that a need 
to define an argument called self? Here's some code where I'm modularizing a 
recaptcha test to a function and the I must add the parameter "self" to the 
function is_submitter_human:


class A(BaseHandler, blobstore_handlers.BlobstoreUploadHandler):
def is_submitter_human(self):
cResponse = captcha.submit( 
self.request.get('recaptcha_challenge_field').encode('utf-8'),  
   self.request.get('recaptcha_response_field').encode('utf-8'),
 CAPTCHA_PRV_KEY,
 os.environ['REMOTE_ADDR'])
return cResponse.is_valid

def post(self, view):
logging.debug('starting recaptcha check')
isHuman = self.is_submitter_human()# here I don't pass a parameter
logging.debug('recaptcha check isHuman:' +str(isHuman))
if not isHuman:#failed captcha and can try again
#Reprint the form

--
It seems unlike other programming languages where the number of arguments in 
the call are the same as the number of arguments in the function head and 
python requires me to add one parameter to the function head and I wonder if 
you call tell me something about the background why?

What's the story of using these parameters that are called "self"?

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


Some problems refer to install 3rd party package of Python on mac OS 10.6.8

2011-08-28 Thread Gee Chen
--
the Python environment on my mac is:

Python 2.6.4 (r264:75706, Aug 28 2011, 22:29:24)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin

i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5664)
Copyright (C) 2007 Free Software Foundation, Inc.
-


I found the download adresses of scipy and numpy from official website
'www.scipy.org'. After downloading 2 latest released dmg files, i
directly installed them with double-click the dmg files.

Then, i opened Python interpreter in Terminal, and tested whether
scipy & numpy work. The result is disappointed!

when i inputed ' import scipy' & 'import numpy', the output is :


>>> import scipy
Traceback (most recent call last):
File "", line 1, in 
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/
site-packages/scipy/_init_.py", line 78, in 
from numpy import show_config as show_numpy_config
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/
site-packages/numpy/_init_.py", line 137, in 
import add_newdocs
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/
site-packages/numpy/add_newdocs.py", line 9, in 
from numpy.lib import add_newdoc
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/
site-packages/numpy/lib/_init_.py", line 4, in 
from type_check import *
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/
site-packages/numpy/lib/type_check.py", line 8, in 
import numpy.core.numeric as _nx
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/
site-packages/numpy/core/_init_.py", line 5, in 
import multiarray
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/
lib/python2.6/site-packages/numpy/core/multiarray.so, 2): no suitable
image found. Did find:
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-
packages/numpy/core/multiarray.so: no matching architecture in
universal wrapper
>>>
>>> import numpy
Traceback (most recent call last):
File "", line 1, in 
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/
site-packages/numpy/_init_.py", line 137, in 
import add_newdocs
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/
site-packages/numpy/add_newdocs.py", line 9, in 
from numpy.lib import add_newdoc
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/
site-packages/numpy/lib/_init_.py", line 4, in 
from type_check import *
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/
site-packages/numpy/lib/type_check.py", line 8, in 
import numpy.core.numeric as _nx
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/
site-packages/numpy/core/_init_.py", line 5, in 
import multiarray
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/
lib/python2.6/site-packages/numpy/core/multiarray.so, 2): no suitable
image found. Did find:
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-
packages/numpy/core/multiarray.so: no matching architecture in
universal wrapper
>>>


Is there anybody can tell me where the error exists?


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


Re: Checking Signature of Function Parameter

2011-08-28 Thread Ian Kelly
On Sun, Aug 28, 2011 at 3:20 PM, Travis Parks  wrote:
> I am trying to write an algorithms library in Python. Most of the
> functions will accept functions as parameters. For instance, there is
> a function called any:
>
> def any(source, predicate):
>    for item in source:
>        if predicate(item):
>            return true;
>    return false;

Perhaps not the best name, since there is already a built-in called
"any" that would be masked by this.  Using the built-in, "any(source,
predicate)" would be written as "any(predicate(x) for x in source)"

> I guess my concern is mostly with the delayed exceptions. It is hard
> to find the source of an error when it doesn't happen immediately. I
> am writing this library so all of the calls can be chained together
> (composed). If this nesting gets really deep, finding the source is
> hard to do, even with a good debugger.

Agreed that there are cases where it is useful to do this.  But there
is no delayed execution in the example you've given, so the exceptions
will happen immediately (or at least, within the same stack frame).
The stack traces will still come from the "any" function and will look
basically the same as the stack traces you'll get from raising the
exceptions by hand.

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


Re: Some problems refer to install 3rd party package of Python on mac OS 10.6.8

2011-08-28 Thread Chris Rebert
On Sun, Aug 28, 2011 at 5:35 PM, Gee Chen  wrote:
> --
> the Python environment on my mac is:
>
> Python 2.6.4 (r264:75706, Aug 28 2011, 22:29:24)
> [GCC 4.2.1 (Apple Inc. build 5664)] on darwin

For future reference, when on OS X, it's very helpful to include how
you installed your Python, and whether it's 32-bit or 64-bit.


> I found the download adresses of scipy and numpy from official website
> 'www.scipy.org'. After downloading 2 latest released dmg files, i
> directly installed them with double-click the dmg files.
>
> Then, i opened Python interpreter in Terminal, and tested whether
> scipy & numpy work. The result is disappointed!
>
> when i inputed ' import scipy' & 'import numpy', the output is :
>
>
 import scipy
> Traceback (most recent call last):

> File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/
> site-packages/numpy/core/_init_.py", line 5, in 
> import multiarray
> ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/
> lib/python2.6/site-packages/numpy/core/multiarray.so, 2): no suitable
> image found. Did find:
> /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-
> packages/numpy/core/multiarray.so: no matching architecture in
> universal wrapper

> Is there anybody can tell me where the error exists?

I believe you've installed 32-bit libraries for a 64-bit Python (or
possibly vice-versa). It appears that NumPy & SciPy official releases
are 32-bit-only. So, you can either use the alternate, unofficial
64-bit releases of those packages, or install a 32-bit Python (via
Fink, MacPorts, a Python.org installer, etc.). A third option is to
install the Enthought Python Distribution
(http://www.enthought.com/products/epd.php ) or similar, which bundles
Python together with SciPy, NumPy, and other libraries in a single
install.

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


Re: Checking Signature of Function Parameter

2011-08-28 Thread Chris Rebert
On Sun, Aug 28, 2011 at 2:20 PM, Travis Parks  wrote:
> I am trying to write an algorithms library in Python. Most of the
> functions will accept functions as parameters. For instance, there is
> a function called any:
>
> def any(source, predicate):
>    for item in source:
>        if predicate(item):
>            return true;
>    return false;
>
> There are some things I want to make sure of. 1) I want to make sure
> that source is iterable. 2) More importantly, I want to make sure that
> predicate is callable, accepting a thing, returning a bool.

> I am more concerned with the number of parameters.

That can be introspected using the `inspect` module:
http://docs.python.org/library/inspect.html#inspect.getargspec

> Finally, can I use decorators to automatically perform these checks,
> instead of hogging the top of all my methods?

Certainly. Although, as others have said, the cost-benefit ratio of
adding code to perform such somewhat-redundant checks might make it
not worth the trouble.

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


killing a script

2011-08-28 Thread Russ P.
I have a Python (2.6.x) script on Linux that loops through many
directories and does processing for each. That processing includes
several "os.system" calls for each directory (some to other Python
scripts, others to bash scripts).

Occasionally something goes wrong, and the top-level script just keeps
running with a stack dump for each case. When I see that, I want to
just kill the whole thing and fix the bug. However, when I hit Control-
C, it apparently just just kills whichever script happens to be
running at that instant, and the top level script just moves to the
next line and keeps running. If I hit Control-C repeatedly, I
eventually get "lucky" and kill the top-level script. Is there a
simple way to ensure that the first Control-C will kill the whole darn
thing, i.e, the top-level script? Thanks.

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


Re: Why I need the parameter when the call doesn't use it?

2011-08-28 Thread Ben Finney
Niklas Rosencrantz  writes:

> I modularize code for a webapp and I want to know what python makes
> that a need to define an argument called self?

Because, when calling a method on an instance, the instance is a
parameter to the call. That is,

foo = Thribble()
foo.bar("spam")

is usually syntactic sugar for

foo = Thribble()
foo.__class__.bar(foo, "spam")

and so the definition of that function on the Thribble class needs to
accept both parameters.

> Here's some code where I'm modularizing a recaptcha test to a function
> and the I must add the parameter "self" to the function
> is_submitter_human

Yes, because the code of ‘is_submitter_human’ needs to know *which*
instance has been passed. That instance is bound to the first parameter,
which is conventionally named ‘self’.

> It seems unlike other programming languages where the number of
> arguments in the call are the same as the number of arguments in the
> function head and python requires me to add one parameter to the
> function head and I wonder if you call tell me something about the
> background why?

I hope that explains.

See also:

http://docs.python.org/faq/programming.html#what-is-self>
http://docs.python.org/faq/design.html#why-self>

-- 
 \  “Nullius in verba” (“Take no-one's word for it”) —motto of the |
  `\   Royal Society, since 1663-06-30 |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Python] Why I need the parameter when the call doesn't use it?

2011-08-28 Thread Chris Gonnerman

On 08/28/2011 07:26 PM, Niklas Rosencrantz wrote:

I modularize code for a webapp and I want to know what python makes that a need to define 
an argument called self? Here's some code where I'm modularizing a recaptcha test to a 
function and the I must add the parameter "self" to the function 
is_submitter_human:


class A(BaseHandler, blobstore_handlers.BlobstoreUploadHandler):
 def is_submitter_human(self):
is_submitter_human() isn't a function, it's a method.  Methods are 
always called with a reference to the class instance (i.e. the object) 
that the method belongs to; this reference is the first argument, and is 
conventionally called "self".


Though I've hacked it out, your code sample includes calls to other 
methods of the object, by calling self.methodname().  Without the first 
parameter, how else would you do it?


-- Chris.


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


Button Label change on EVT_BUTTON in wxpython!!!

2011-08-28 Thread Ven
Some system info before proceeding further:

Platform: Mac OS X 10.7.1
Python Version: ActiveState Python 2.7.1
wxPython Version: [url=http://downloads.sourceforge.net/wxpython/
wxPython2.9-osx-2.9.2.1-cocoa-py2.7.dmg]wxPython2.9-osx-cocoa-py2.7[/
url]

I want the button label to be changed while performing a task

So, here is what I did/want:

self.run_button=wx.Button(self.panel,ID_RUN_BUTTON,label='Install')
self.Bind(wx.EVT_BUTTON, self.OnRun,id=ID_RUN_BUTTON)

def OnRun(self,evt):
self.run_button.SetLabel('Installing..')
#call a function that does the installation task
installation_task()
#After task completion, set the button label back to "Install"
self.run_button.SetLabel('Install')

When I try doing this, it doesn't set the label to "Installing" while
the task is being performed. Any suggestions how do I achieve this?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why I need the parameter when the call doesn't use it?

2011-08-28 Thread Chris Rebert
On Sun, Aug 28, 2011 at 5:26 PM, Niklas Rosencrantz  wrote:
> I modularize code for a webapp and I want to know what python makes that a 
> need to define an argument called self? Here's some code where I'm 
> modularizing a recaptcha test to a function and the I must add the parameter 
> "self" to the function is_submitter_human:
>
> 
> class A(BaseHandler, blobstore_handlers.BlobstoreUploadHandler):
>    def is_submitter_human(self):
>        cResponse = captcha.submit(                     
> self.request.get('recaptcha_challenge_field').encode('utf-8'),                
>      self.request.get('recaptcha_response_field').encode('utf-8'),
>                     CAPTCHA_PRV_KEY,
>                     os.environ['REMOTE_ADDR'])
>        return cResponse.is_valid
>
>    def post(self, view):
>        logging.debug('starting recaptcha check')
>        isHuman = self.is_submitter_human()# here I don't pass a parameter
>        logging.debug('recaptcha check isHuman:' +str(isHuman))
>        if not isHuman:#failed captcha and can try again
>            #Reprint the form
>
> --
> It seems unlike other programming languages where the number of arguments in 
> the call are the same as the number of arguments in the function head and 
> python requires me to add one parameter to the function head and I wonder if 
> you call tell me something about the background why?
>
> What's the story of using these parameters that are called "self"?

Some other languages name the analogous parameter "this" instead of
"self", and basically declare it implicitly for you. In both cases,
said variable is used to refer to the object that the current method
is being called on (e.g. if `w` is a list and I do w.append(v), the
list `w` is `self` in the context of the .append() method call). Since
Python's object-orientation is slightly impure, you are required to
declare `self` explicitly in the parameter list, unlike most other
languages. Technically, you are free to name the parameter something
else instead of "self"; naming it "self" is merely a convention.
However, no matter its name, the first parameter to a method will
always receive the current object as its argument value.

So, given: x = Foo()
Then: x.bar(y, z)
is approximately equivalent to:
Foo.bar(x, y, z) # perfectly legal working code

So the number of arguments actually /does/ match the number of
parameters; `x`/`self` is just passed implicitly via the semantics of
the dot (".") operator.

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


Re: killing a script

2011-08-28 Thread MRAB

On 29/08/2011 02:15, Russ P. wrote:

I have a Python (2.6.x) script on Linux that loops through many
directories and does processing for each. That processing includes
several "os.system" calls for each directory (some to other Python
scripts, others to bash scripts).

Occasionally something goes wrong, and the top-level script just keeps
running with a stack dump for each case. When I see that, I want to
just kill the whole thing and fix the bug. However, when I hit Control-
C, it apparently just just kills whichever script happens to be
running at that instant, and the top level script just moves to the
next line and keeps running. If I hit Control-C repeatedly, I
eventually get "lucky" and kill the top-level script. Is there a
simple way to ensure that the first Control-C will kill the whole darn
thing, i.e, the top-level script? Thanks.


You could look at the return value of os.system, which may tell you the
exit status of the process.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Button Label change on EVT_BUTTON in wxpython!!!

2011-08-28 Thread Philip Semanchuk

On Aug 28, 2011, at 9:30 PM, Ven wrote:

> Some system info before proceeding further:
> 
> Platform: Mac OS X 10.7.1
> Python Version: ActiveState Python 2.7.1
> wxPython Version: [url=http://downloads.sourceforge.net/wxpython/
> wxPython2.9-osx-2.9.2.1-cocoa-py2.7.dmg]wxPython2.9-osx-cocoa-py2.7[/
> url]
> 
> I want the button label to be changed while performing a task
> 
> So, here is what I did/want:
> 
> self.run_button=wx.Button(self.panel,ID_RUN_BUTTON,label='Install')
> self.Bind(wx.EVT_BUTTON, self.OnRun,id=ID_RUN_BUTTON)
> 
> def OnRun(self,evt):
>   self.run_button.SetLabel('Installing..')
>   #call a function that does the installation task
>   installation_task()
>   #After task completion, set the button label back to "Install"
>   self.run_button.SetLabel('Install')
> 
> When I try doing this, it doesn't set the label to "Installing" while
> the task is being performed. Any suggestions how do I achieve this?


Suggestion #1: After you set the label to "Installing...", try adding 
self.run_button.Refresh() and/or self.run_button.Update().

Suggestion #2: Ask wxPython questions on the wxPython mailing list.

Good luck
Philip

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


Re: [Python] Why I need the parameter when the call doesn't use it?

2011-08-28 Thread Ben Finney
Chris Gonnerman  writes:

> On 08/28/2011 07:26 PM, Niklas Rosencrantz wrote:
> > class A(BaseHandler, blobstore_handlers.BlobstoreUploadHandler):
> >  def is_submitter_human(self):

> is_submitter_human() isn't a function, it's a method.

No, that's not true and may lead to future confusion.

Rather, it is a function *and* a method. Not all functions are methods,
but all methods are functions.

> Methods are always called with a reference to the class instance

Also not true, but perhaps too subtle an issue to explore in this thread.

> Though I've hacked it out, your code sample includes calls to other
> methods of the object, by calling self.methodname(). Without the first
> parameter, how else would you do it?

Yes, that's exactly the reason. Thanks.

-- 
 \ “A child of five could understand this. Fetch me a child of |
  `\  five.” —Groucho Marx |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: killing a script

2011-08-28 Thread Russ P.
On Aug 28, 6:52 pm, MRAB  wrote:
> On 29/08/2011 02:15, Russ P. wrote:> I have a Python (2.6.x) script on Linux 
> that loops through many
> > directories and does processing for each. That processing includes
> > several "os.system" calls for each directory (some to other Python
> > scripts, others to bash scripts).
>
> > Occasionally something goes wrong, and the top-level script just keeps
> > running with a stack dump for each case. When I see that, I want to
> > just kill the whole thing and fix the bug. However, when I hit Control-
> > C, it apparently just just kills whichever script happens to be
> > running at that instant, and the top level script just moves to the
> > next line and keeps running. If I hit Control-C repeatedly, I
> > eventually get "lucky" and kill the top-level script. Is there a
> > simple way to ensure that the first Control-C will kill the whole darn
> > thing, i.e, the top-level script? Thanks.
>
> You could look at the return value of os.system, which may tell you the
> exit status of the process.

Thanks for the suggestion. Yeah, I guess I could do that, but it seems
that there should be a simpler way to just kill the "whole enchilada."
Hitting Control-C over and over is a bit like whacking moles.

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


Re: killing a script

2011-08-28 Thread Chris Angelico
On Mon, Aug 29, 2011 at 12:41 PM, Russ P.  wrote:
> On Aug 28, 6:52 pm, MRAB  wrote:
>> You could look at the return value of os.system, which may tell you the
>> exit status of the process.
>
> Thanks for the suggestion. Yeah, I guess I could do that, but it seems
> that there should be a simpler way to just kill the "whole enchilada."
> Hitting Control-C over and over is a bit like whacking moles.

I believe the idea of this suggestion is for the outer script to
notice that the inner script terminated via Ctrl-C, and would then
immediately choose to terminate itself - thus avoiding the
whack-a-mole effect.

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


Re: killing a script

2011-08-28 Thread Paul Rubin
"Russ P."  writes:
> Thanks for the suggestion. Yeah, I guess I could do that, but it seems
> that there should be a simpler way to just kill the "whole enchilada."
> Hitting Control-C over and over is a bit like whacking moles.

Hit Ctrl-Z, which stops execution of the subprogram but doesn't kill it.
Then kill both the subprogram and the control program from a terminal
window.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] Oktest 0.9.0 released - a new-style testing library

2011-08-28 Thread Makoto Kuwata
I published presentation slide about Oktest.
If you have interested in testing, check it out.

http://www.slideshare.net/kwatch/oktest-a-new-style-testing-library-for-python


--
regards,
makoto kuwata


On Sat, Aug 27, 2011 at 9:37 PM, Makoto Kuwata  wrote:
> Hi,
>
> I released Oktest 0.9.0.
> http://pypi.python.org/pypi/Oktest/
> http://packages.python.org/Oktest/
>
> Oktest is a new-style testing library for Python.
> ::
>
>    from oktest import ok, NG
>    ok (x) > 0                 # same as assert_(x > 0)
>    ok (s) == 'foo'            # same as assertEqual(s, 'foo')
>    ok (s) != 'foo'            # same as assertNotEqual(s, 'foo')
>    ok (f).raises(ValueError)  # same as assertRaises(ValueError, f)
>    ok (u'foo').is_a(unicode)  # same as assert_(isinstance(u'foo', unicode))
>    NG (u'foo').is_a(int)      # same as assert_(not isinstance(u'foo', int))
>    ok ('A.txt').is_file()     # same as assert_(os.path.isfile('A.txt'))
>    NG ('A.txt').is_dir()      # same as assert_(not os.path.isdir('A.txt'))
>
> See http://packages.python.org/Oktest/ for details.
>
> NOTICE!! Oktest is a young project and specification may change in the future.
>
>
> Main Enhancements
> -
>
> * New '@test' decorator provided. It is simple but very powerful.
>  Using @test decorator, you can write test description in free text
>  instead of test method.
>  ex::
>
>    class FooTest(unittest.TestCase):
>
>        def test_1_plus_1_should_be_2(self):  # not cool...
>            self.assertEqual(2, 1+1)
>
>        @test("1 + 1 should be 2")    # cool! easy to read & write!
>        def _(self):
>            self.assertEqual(2, 1+1)
>
> * Fixture injection support by '@test' decorator.
>  Arguments of test method are regarded as fixture names and
>  they are injected by @test decorator automatically.
>  Instance methods or global functions which name is 'provide_' are
>  regarded as fixture provider (or builder) for fixture ''.
>  ex::
>
>    class SosTest(unittest.TestCase):
>
>        ##
>        ## fixture providers.
>        ##
>        def provide_member1(self):
>            return {"name": "Haruhi"}
>
>        def provide_member2(self):
>            return {"name": "Kyon"}
>
>        ##
>        ## fixture releaser (optional)
>        ##
>        def release_member1(self, value):
>            assert value == {"name": "Haruhi"}
>
>        ##
>        ## testcase which requires 'member1' and 'member2' fixtures.
>        ##
>        @test("validate member's names")
>        def _(self, member1, member2):
>            assert member1["name"] == "Haruhi"
>            assert member2["name"] == "Kyon"
>
>  Dependencies between fixtures are resolved automatically.
>  ex::
>
>    class BarTest(unittest.TestCase):
>
>        ##
>        ## for example:
>        ## - Fixture 'a' depends on 'b' and 'c'.
>        ## - Fixture 'c' depends on 'd'.
>        ##
>        def provide_a(b, c):  return b + c + ["A"]
>        def provide_b():      return ["B"]
>        def provide_c(d):     return d + ["C"]
>        def provide_d():      reutrn ["D"]
>
>        ##
>        ## Dependencies between fixtures are solved automatically.
>        ##
>        @test("dependency test")
>        def _(self, a):
>            assert a == ["B", "D", "C", "A"]
>
>  If loop exists in dependency then @test reports error.
>
>  If you want to integrate with other fixture library, see the following
>  example::
>
>      class MyFixtureManager(object):
>          def __init__(self):
>              self.values = { "x": 100, "y": 200 }
>          def provide(self, name):
>              return self.values[name]
>          def release(self, name, value):
>              pass
>
>      oktest.fixure_manager = MyFixtureResolver()
>
>
>
> Other Enhancements and Changes
> --
>
> * Supports command-line interface to execute test scripts.
> * Reporting style is changed.
> * New assertion method ``ok(x).attr(name, value)`` to check attribute.
> * New assertion method ``ok(x).length(n)``.
> * New feature``ok().should`` helps you to check boolean method.
> * 'ok(str1) == str2' displays diff if text1 != text2, even when using
>  with unittest module.
> * Assertion ``raises()`` supports regular expression to check error message.
> * Helper functions in oktest.dummy module are now available as decorator.
> * 'AssertionObject.expected' is renamed to 'AssertionObject.boolean'.
> * ``oktest.run()`` is changed to return number of failures and errors of 
> tests.
> * ``before_each()`` and ``after_each()`` are now non-supported.
> * (Experimental) New function ``NOT()`` provided which is same as ``NG()``.
> * (Experimental) ``skip()`` and ``@skip.when()`` are provided to skip tests::
>
> See CHANGES.txt for details.
> http://packages.python.org/Oktest/CHANGES.txt
>
>
> Have a nice testing life!
>
> --
> regards,
> makoto kuwata
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: killing a script

2011-08-28 Thread Russ P.
On Aug 28, 7:51 pm, Chris Angelico  wrote:
> On Mon, Aug 29, 2011 at 12:41 PM, Russ P.  wrote:
> > On Aug 28, 6:52 pm, MRAB  wrote:
> >> You could look at the return value of os.system, which may tell you the
> >> exit status of the process.
>
> > Thanks for the suggestion. Yeah, I guess I could do that, but it seems
> > that there should be a simpler way to just kill the "whole enchilada."
> > Hitting Control-C over and over is a bit like whacking moles.
>
> I believe the idea of this suggestion is for the outer script to
> notice that the inner script terminated via Ctrl-C, and would then
> immediately choose to terminate itself - thus avoiding the
> whack-a-mole effect.
>
> ChrisA

Yes, but if I am not mistaken, that will require me to put a line or
two after each os.system call. That's almost like whack-a-mole at the
code level rather than the Control-C level. OK, not a huge deal for
one script, but I was hoping for something simpler. I was hoping I
could put one line at the top of the script and be done with it.

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


Re: killing a script

2011-08-28 Thread Chris Rebert
On Sun, Aug 28, 2011 at 8:08 PM, Russ P.  wrote:
> On Aug 28, 7:51 pm, Chris Angelico  wrote:
>> On Mon, Aug 29, 2011 at 12:41 PM, Russ P.  wrote:
>> > On Aug 28, 6:52 pm, MRAB  wrote:
>> >> You could look at the return value of os.system, which may tell you the
>> >> exit status of the process.
>>
>> > Thanks for the suggestion. Yeah, I guess I could do that, but it seems
>> > that there should be a simpler way to just kill the "whole enchilada."
>> > Hitting Control-C over and over is a bit like whacking moles.
>>
>> I believe the idea of this suggestion is for the outer script to
>> notice that the inner script terminated via Ctrl-C, and would then
>> immediately choose to terminate itself - thus avoiding the
>> whack-a-mole effect.
>>
>> ChrisA
>
> Yes, but if I am not mistaken, that will require me to put a line or
> two after each os.system call.

Er, just write a wrapper for os.system(), e.g.:

def mysystem(cmd):
if os.system(cmd):
sys.exit()

Also, you may want to switch to using the `subprocess` module instead.

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


Re: killing a script

2011-08-28 Thread Russ P.
On Aug 28, 8:16 pm, Chris Rebert  wrote:
> On Sun, Aug 28, 2011 at 8:08 PM, Russ P.  wrote:
> > On Aug 28, 7:51 pm, Chris Angelico  wrote:
> >> On Mon, Aug 29, 2011 at 12:41 PM, Russ P.  wrote:
> >> > On Aug 28, 6:52 pm, MRAB  wrote:
> >> >> You could look at the return value of os.system, which may tell you the
> >> >> exit status of the process.
>
> >> > Thanks for the suggestion. Yeah, I guess I could do that, but it seems
> >> > that there should be a simpler way to just kill the "whole enchilada."
> >> > Hitting Control-C over and over is a bit like whacking moles.
>
> >> I believe the idea of this suggestion is for the outer script to
> >> notice that the inner script terminated via Ctrl-C, and would then
> >> immediately choose to terminate itself - thus avoiding the
> >> whack-a-mole effect.
>
> >> ChrisA
>
> > Yes, but if I am not mistaken, that will require me to put a line or
> > two after each os.system call.
>
> Er, just write a wrapper for os.system(), e.g.:
>
> def mysystem(cmd):
>     if os.system(cmd):
>         sys.exit()
>
> Also, you may want to switch to using the `subprocess` module instead.
>
> Cheers,
> Chris

Sounds like a good idea. I'll give it a try. Thanks.

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


Re: Why I need the parameter when the call doesn't use it?

2011-08-28 Thread John Gordon
In <66a3f64c-d35e-40c7-be69-ddf708e37...@glegroupsg2000goo.googlegroups.com> 
Niklas Rosencrantz  writes:

> What's the story of using these parameters that are called "self"?

"self" is a reference to the class object, and it allows the method to
access other methods and variables within the class.

For example, say you have this class:

  class MyClass(object):

def method1(self, x):
  self.x = x
  self.say_hello()

def say_hello(self):
  self.x = self.x + 1
  print "hello"

Without the "self" reference, method1 wouldn't be able to access
instance variable x and it wouldn't be able to call say_hello().

If you have a method that doesn't need to access other variables or
methods within the class, you can declare it with the @staticmethod
decorator.

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

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


Re: about if __name == '__main__':

2011-08-28 Thread Amit Jaluf
On Aug 28, 12:51 pm, Ian Kelly  wrote:
> On Sun, Aug 28, 2011 at 9:34 AM, Amit Jaluf  wrote:
> > hello group
>
> > i have one question about this
>
> > if __name == '__main__':

sorry dear for this
and thanks all of you for this
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: packaging a python application

2011-08-28 Thread anand jeyahar
Hi all,
This is interesting. Do we have the distribute/setuptools equivalent of
postinstall (with ncurses interface) from Debian? My limited foray into
setuptools, indicate it doesn't have .
Is it a planned feature either? i would like to contribute in that case.

==
Anand Jeyahar
https://sites.google.com/site/
anandjeyahar
==
The man who is really serious,
with the urge to find out what truth is,
has no style at all. He lives only in what is.
  ~Bruce Lee

Love is a trade with lousy accounting policies.
 ~Aang Jie



On Sun, Aug 28, 2011 at 06:22, suresh  wrote:

> Hi
> I created a python application which consists of multiple python files and
> a configuration file. I am not sure, how can I distribute it.
>
> I read distutils2 documentation and a few blogs on python packaging. But I
> still have the following questions.
>
> 1. My package has a configuration file which has to be edited by the user.
> How do we achieve that?
>
> 2. Should the user directly edit the configuration file, or there would be
> an interface for doing it...?(I remember my sendmail installations in
> Debian/Ubuntu. It would ask a bunch of questions and the cfg file would be
> ready)
>
> I am just confused how to go about...
>
> thanks
> suresh
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Python] Why I need the parameter when the call doesn't use it?

2011-08-28 Thread Steven D'Aprano
On Mon, 29 Aug 2011 12:34 pm Ben Finney wrote:

> Chris Gonnerman  writes:
> 
>> On 08/28/2011 07:26 PM, Niklas Rosencrantz wrote:
>> > class A(BaseHandler, blobstore_handlers.BlobstoreUploadHandler):
>> >  def is_submitter_human(self):
> 
>> is_submitter_human() isn't a function, it's a method.
> 
> No, that's not true and may lead to future confusion.
> 
> Rather, it is a function *and* a method. Not all functions are methods,
> but all methods are functions.

Wouldn't it be more accurate to say that methods *wrap* functions?

>>> class C(object):
... def spam(self):
... pass
...
>>> C().spam
>
>>> C().spam.im_func



(At least for pure Python methods... those written in C, such as for the
built-in types, don't.)


>> Methods are always called with a reference to the class instance
> 
> Also not true, but perhaps too subtle an issue to explore in this thread.

But for the record, you have "normal" instance methods, class methods,
static methods, and any other sort of method you can create using the
descriptor protocol, such as this one:

http://code.activestate.com/recipes/577030-dualmethod-descriptor/

But as Ben hints at, this is getting into fairly advanced territory.



-- 
Steven

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


Interact with SQL Database using Python 2.4 or lower

2011-08-28 Thread Sascha
Hello

I have an website on an Australian webhost. I have designed my website
to allow people to login & their login details are stored in an
SQLite3 database. I interact with the SQLite3 database using pythons
SQLite3 module(found only in python2.5 & up)

My Problem: the webhost runs Python 2.4 so I cannot communicate
with(query or modify) my SQLite3 database. The webhost will not allow
me to install my own version of python or upload modules unless I
upgrade to VPS.

What do you think are my options to still be able to work/interface
with my SQL database? Do you know of way to interact with a SQL
database using python modules from Python 2.4 or earlier?

Do you know of a python 2.4 module that will let me interact with an
SQL database(can be MySQL, SQLite, etc.)?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Interact with SQL Database using Python 2.4 or lower

2011-08-28 Thread Stephen Hansen
On 8/28/11 9:49 PM, Sascha wrote:
> My Problem: the webhost runs Python 2.4 so I cannot communicate
> with(query or modify) my SQLite3 database. The webhost will not allow
> me to install my own version of python or upload modules unless I
> upgrade to VPS.

Get a new webhost. Seriously. This is a seriously absurd requirement --
it goes past absurd into malicious incompetence, frankly. Not being able
to upload your own modules?

There has to be another option. Personally, I'm a major fan of
Webfaction -- from price to plans to what's supported to actual
effectiveness of their tech support.

But I don't know if they have a warehouse in Australia, if their latency
with any of their various data centers is suitable for you. Maybe, maybe
not -- but there /has/ to be a better option then this site... Good
hosts these days are not all that uncommon and are fairly competitive.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Interact with SQL Database using Python 2.4 or lower

2011-08-28 Thread Chris Angelico
On Mon, Aug 29, 2011 at 3:09 PM, Stephen Hansen
 wrote:
> Get a new webhost. ...
>
> But I don't know if they have a warehouse in Australia, if their latency
> with any of their various data centers is suitable for you. Maybe, maybe
> not -- but there /has/ to be a better option then this site... Good
> hosts these days are not all that uncommon and are fairly competitive.

Having burnt my fingers with a couple of web hosts, and finally
decided to host my own web site, I have one major piece of advice
regarding this:

Get a personal recommendation.

Don't sign up with any hosting service unless you have advice from
someone you trust who has used that service and been happy with it.
I'm sure good hosts aren't uncommon, but nor are bad hosts, and it's
easy to get caught up with a lot of hassles and outages.

BTW, don't take the fact that I host my own site as a negative
recommendation for every hosting company out there. My requirements
are somewhat unusual - I want to host a MUD, not just a web site.
Hosts that let you do THAT much are usually quite expensive :)

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


Re: Interact with SQL Database using Python 2.4 or lower

2011-08-28 Thread Stephen Hansen
On 8/28/11 10:23 PM, Chris Angelico wrote:
> On Mon, Aug 29, 2011 at 3:09 PM, Stephen Hansen
>  wrote:
>> Get a new webhost. ...
>>
>> But I don't know if they have a warehouse in Australia, if their latency
>> with any of their various data centers is suitable for you. Maybe, maybe
>> not -- but there /has/ to be a better option then this site... Good
>> hosts these days are not all that uncommon and are fairly competitive.
> 
> Having burnt my fingers with a couple of web hosts, and finally
> decided to host my own web site, I have one major piece of advice
> regarding this:
> 
> Get a personal recommendation.

This is good advice, though with prices as they are in many cases --
provided you don't need to start out immediately solid and have some
development wiggle-room -- its not a bad thing to experiment.

Just don't get too tied to a certain host until you feel them out.
Sending them emails with detailed questions before you sign up is a good
thing, for example.

Good hosts will respond with detailed, specific answers, from real
people. Bad hosts will point you to a vague website or stock reply.

Real people, reading your real questions, and answering with real
answers is a major, major sign of the kind of company I want to do
business with. (Bonus points if they respond to complex, technical and
legal questions with specific answers within 24 hours -- bonus++ points
if the non-legal questions usually get responses in 1, at absurd times
even).

> BTW, don't take the fact that I host my own site as a negative
> recommendation for every hosting company out there. My requirements
> are somewhat unusual - I want to host a MUD, not just a web site.
> Hosts that let you do THAT much are usually quite expensive :)

Hehe, I don't want to get overly advertising in my comments (so I'm so
not including a referrer link anywhere), but amusingly enough, my first
Webfaction account was signed up for the MUD reason.

They officially don't give a rats ass what you run in the background,
provided you're just not using more then your RAM allotment and that its
not spiking the CPU to a point that affects the rest of the system.

I have one account that runs a mud, one that does often semi-significant
background processing regularly via cron jobs (which they mailed me
about once when it got out of hand-- but they were entirely professional
and nice about it, and I fixed it with some controls so it behaved in a
more friendly way towards the rest of the system), and one for my
personal site where I run an IRC bouncer on, and all is cool.

(Why three accounts? One is paid for by a client, one half by me, one by
me -- it was just easier, and no way it all would fit under a single plan)

Anyways. I shall not further ramble as a satisfied-customer.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: On re / regex replacement

2011-08-28 Thread jmfauth
On 28 août, 20:40, MRAB  wrote:
> ...

> The regex module tries to be drop-in compatible. It supports the LOCALE
> flag only because the re module has it. Even Perl has something similar.
>  ...


Ok. That's quite logical.

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


Web hosting when you need to install your own modules (was Re: Interact with SQL Database using Python 2.4 or lower)

2011-08-28 Thread Chris Angelico
On Mon, Aug 29, 2011 at 3:39 PM, Stephen Hansen
 wrote:
> Just don't get too tied to a certain host until you feel them out.
> Sending them emails with detailed questions before you sign up is a good
> thing, for example.
>

That helps a lot, but the problems I had with my most recent pay-for
web host were less obvious:

* Outages that were scheduled, but not notified in a way that I had
noticed (it was on their web site, but they didn't mail my registered
other email address)
* Fine print on their uptime policy that explicitly excluded scheduled
outages, and considerably lengthier and more numerous scheduled
outages than I would have normally considered reasonable
* DNS record changes required a support ticket (this was shared web
hosting, so I didn't have control over the BIND files - that's what
they said, anyway)
* Some sort of weird lack of internal communication that meant that
they didn't ever close our account. I still, to this day, am getting
emails from their server saying "Hey, you have some package-installed
software that's out of date, you should log in and update it". I
cannot log in as our account has been suspended for non-payment. I
cannot close the account as it is suspended. They somehow didn't get
the message four months before the suspension, following their policy
strictly, requesting closure.

So... yeah. Hopefully, this is a rare situation, but that's why I
would look for a personal reference.

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


Re: Web hosting when you need to install your own modules (was Re: Interact with SQL Database using Python 2.4 or lower)

2011-08-28 Thread Stephen Hansen
On 8/28/11 10:52 PM, Chris Angelico wrote:
> * DNS record changes required a support ticket (this was shared web
> hosting, so I didn't have control over the BIND files - that's what
> they said, anyway)

Ouch: I never let a webhost near my domain names. I was burned somewhere
around that a long time ago, and now always keep the jobs of managing my
DNS record and hosting my sites /totally/ separate.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why I need the parameter when the call doesn't use it?

2011-08-28 Thread Ben Finney
John Gordon  writes:

> In <66a3f64c-d35e-40c7-be69-ddf708e37...@glegroupsg2000goo.googlegroups.com> 
> Niklas Rosencrantz  writes:
>
> > What's the story of using these parameters that are called "self"?
>
> "self" is a reference to the class object, and it allows the method to
> access other methods and variables within the class.

No, ‘self’ (in an instance method, which is where it's normally used) is
bound to the instance object. The class object is a different thing.

-- 
 \ “Alternative explanations are always welcome in science, if |
  `\   they are better and explain more. Alternative explanations that |
_o__) explain nothing are not welcome.” —Victor J. Stenger, 2001-11-05 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Checking Signature of Function Parameter

2011-08-28 Thread Nobody
On Sun, 28 Aug 2011 14:20:11 -0700, Travis Parks wrote:

> More importantly, I want to make sure that
> predicate is callable, accepting a thing, returning a bool.

The "callable" part is do-able, the rest isn't.

The predicate may accept an arbitrary set of arguments via the "*args"
and/or "**kwargs" syntax, and pass these on to some other function.
Exactly *which* function may be the result of an arbitrarily complex
expression. Or it may not even call another function, but just use the
arbitrary set of arguments in an arbitrarily complex manner.

IOW, determining in advance what will or won't work is actually impossible.

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


Re: killing a script

2011-08-28 Thread Nobody
On Sun, 28 Aug 2011 18:15:56 -0700, Russ P. wrote:

> Is there a
> simple way to ensure that the first Control-C will kill the whole darn
> thing, i.e, the top-level script? Thanks.

You might try using subprocess.Popen() or subprocess.call() rather than
os.system().

os.system() calls the platform's system() function. On Unix, this
specifically ignores SIGINT and SIGQUIT for the duration of the call,
ensuring that Ctrl-C and Ctrl-\ only affect the child process and not the
parent.

subprocess.Popen() doesn't perform any implicit signal handling; it's
implemented in Python in terms of os.fork() and os.execvp[e](). It also
has a better interface (i.e. you get to directly control the argument list
passed to the child process, rather than having to construct a shell
command and hope that you got the quoting/escaping correct).

This may not suffice if any of the descendent processes are moved into
their own process group, as signals generated by the tty driver are sent
only to the foreground process group. However, this is unlikely to be an
issue for simple non-interactive programs (e.g. standard Unix "commands").

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