Re: [Tutor] print "Hello, World!"

2011-02-03 Thread Dharmit Shah
I'd also recommend using
http://www.openbookproject.net/thinkcs/python/english2e/ . Currently I am
learning from it. Once u are through with it u can read the book called Dive
into Python. it's for experienced users. Google it.

Hope that helps.

On Thu, Feb 3, 2011 at 1:20 PM,  wrote:

>
> Seven years ago, my story was similar. I started off with "The Python Quick
> Book" (Manning) and "Python - Visual Quickstart Guide" (Peachpit Press).
> Both are very easy to follow. I still pick up the "Quick" book once in a
> while for reference.
>
> This "Tutor" list helped a lot. I learned by trying out the things people
> offered as solutions to problems from people like you and me.
>
> Asking questions here is a way to help a lot of new Python programmers, and
> a few older ones, too.
>
> There are a lot more resources these days, too. Search on "Python" in
> YouTube.
>
> There are a lot of on-line tutorials, too.
>
>
> - Original Message - From: "Doug Marvel" <
> smokeinourlig...@gmail.com>
> To: 
> Sent: Wednesday, February 02, 2011 6:00 PM
> Subject: [Tutor] print "Hello, World!"
>
>
>  Hey folks,
>>
>> I'm Doug. I've been using computers since second grade, and I know a
>> little about them. I am, however, completely new to programming. I
>> don't even know what I know about it. I'd like some social interaction
>> with this, but I can't go back to school until summer or fall of this
>> year. I don't want to wait to start learning this as I feel like I'm
>> already about a million years behind. I asked the Oracle
>> (www.google.com) and after messing around with the Python Shell and
>> getting a lot of error messages, I decided I need some remote help.
>> Here's where I'm at:
>>
>> - I have downloaded and installed Python 2.6.4. Successfully, I think.
>> - I am running Windows XP SP3 (though I'm going to see if I can do
>> this on my laptop, which has Windows 7)
>> - I have toyed around with some tutorials, but all they really taught
>> me is that I need a teacher.
>>
>> I'm sure you guys are busy, but I read that the most basic questions
>> are okay. As I'm sure there is at least one good resource on the net
>> for people in my position, I'd like some suggestions on where to
>> start. I plan on bothering you all as little as possible, but I am
>> seriously hoping to make real progress between now and my first class.
>> I have a feeling once I get a basic understanding, I'll run away with
>> it. It's just very... big right now. So this list seems like a good
>> thing, but tell me if I'm in the wrong place.
>>
>> I am hoping for a link to a somewhat comprehensive online resource
>> that explains from the beginning in English, plain English, as this is
>> the only language I speak. Something to get my foot in the door would
>> be awesome.
>>
>>
>> Cheers,
>> Doug Marvel
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Regards

Dharmit Shah
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] print "Hello, World!"

2011-02-03 Thread Alan Gauld

"Doug Marvel"  wrote

- I have downloaded and installed Python 2.6.4. Successfully, I 
think.

- I am running Windows XP SP3 (though I'm going to see if I can do
this on my laptop, which has Windows 7)
- I have toyed around with some tutorials, but all they really 
taught

me is that I need a teacher.


:-)

You don't say which tutorials you've looked at but there are a
whole set especially for non programmers on the Python web site
(including mine). They all have slightly different styles and 
approaches

so I suggest you take a look at 2 or 3 and find one that suits you.
Follow it and when you have questins bring them to this list and
we will clarify things for you.


I'm sure you guys are busy, but I read that the most basic questions
are okay.


Yes, thats what we are here for.

I have a feeling once I get a basic understanding, I'll run away 
with

it. It's just very... big right now. So this list seems like a good
thing, but tell me if I'm in the wrong place.


Yes, absolutely. Roll your sleeves up, dive in and experiment a lot.
Then ask questions. Its the best way to learn.


I am hoping for a link to a somewhat comprehensive online resource
that explains from the beginning in English, plain English,


You can try mine, it starts with the basic concepts and takes
you through to writing some basic but real-world programs.
It does assume you know computer basics but you sound as
if you do.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] RE module is working ?

2011-02-03 Thread Karim


Hello,

Any news on this topic?O:-)

Regards
Karim

On 02/02/2011 08:21 PM, Karim wrote:


Hello,

I am trying to subsitute a '""' pattern in '\"\"' namely escape 2 
consecutives double quotes:


* *In Python interpreter:*

$ python
Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> expression = *' "" '*
>>> re.subn(*r'([^\\])?"', r'\1\\"', expression*)
Traceback (most recent call last):
  File "", line 1, in 
  File "/home/karim/build/python/install/lib/python2.7/re.py", line 
162, in subn

return _compile(pattern, flags).subn(repl, string, count)
  File "/home/karim/build/python/install/lib/python2.7/re.py", line 
278, in filter

return sre_parse.expand_template(template, match)
  File "/home/karim/build/python/install/lib/python2.7/sre_parse.py", 
line 787, in expand_template

raise error, "unmatched group"
sre_constants.error: unmatched group

But if I remove '?' I get the following:

>>> re.subn(r'([^\\])"', r'\1\\"', expression)
(' \\"" ', 1)

Only one substitution..._But this is not the same REGEX._ And the 
count=2 does nothing. By default all occurrence shoul be substituted.


* *On linux using my good old sed command, it is working with my
  '?' (0-1 match):*

*$* echo *' "" '* | sed *'s/\([^\\]\)\?"/\1\\"/g*'*
 \"\"

*Indeed what's the matter with RE module!?*

*Any idea will be welcome!

Regards
Karim*
*


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] RE module is working ?

2011-02-03 Thread Steven D'Aprano

Karim wrote:


Hello,

I am trying to subsitute a '""' pattern in '\"\"' namely escape 2 
consecutives double quotes:


You don't have to escape quotes. Just use the other sort of quote:

>>> print '""'
""



   * *In Python interpreter:*

$ python
Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> expression = *' "" '*


No, I'm sorry, that's incorrect -- that gives a syntax error in every 
version of Python I know of, including version 2.7:


>>> expression = *' "" '*
  File "", line 1
expression = *' "" '*
 ^
SyntaxError: invalid syntax


So what are you really running?




 >>> re.subn(*r'([^\\])?"', r'\1\\"', expression*)


Likewise here. *r'...' is a syntax error, as is expression*)

I don't understand what you are running or why you are getting the 
results you are.



> *Indeed what's the matter with RE module!?*

There are asterisks all over your post! Where are they coming from?

What makes you think the problem is with the RE module?

We have a saying in English:

"The poor tradesman blames his tools."

Don't you think it's more likely that the problem is that you are using 
the module wrongly?


I don't understand what you are trying to do, so I can't tell you how to 
do it. Can you give an example of what you want to start with, and what 
you want to end up with? NOT Python code, just literal text, like you 
would type into a letter.


E.g. ABC means literally A followed by B followed by C.
\" means literally backslash followed by double-quote




--
Steven

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] byte array conversion question

2011-02-03 Thread Steven D'Aprano

Bill Allen wrote:

I have found that there are a couple of ways to convert a byte array to a
string in Python.   Is there any advantage or disadvantage to either method?

my_bytes = b'this is a test'

str(my_bytes,'utf-8')   yields 'this is a test'
my_bytes.decode('utf-8';)   yeilds 'this is a test'


Not so far as I know. The decode method is a *tiny* bit faster:

>>> from timeit import Timer
>>> t1 = Timer("str(my_bytes,'utf-8')", "my_bytes = b'this is a test'")
>>> t2 = Timer("my_bytes.decode('utf-8')", "my_bytes = b'this is a test'")
>>> min(t1.repeat())
0.670975923538208
>>> min(t2.repeat())
0.5184659957885742

Those figures are in seconds, for one million calls. So the actual speed 
difference is about 0.1 of a microsecond, almost always too trivial to 
care about.





--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] print "Hello, World!"

2011-02-03 Thread Alan Gauld

"michael scott"  wrote

already been asked, learn from others who asked before you :) Oh 
yea, I once
read that there are no intermediate tutorials in any programming 
language,

because once you get past the basics, you only need to reference the
"documentation" that comes with the language.


Thats very nearly true. There are intermediate level tutorials for a 
few

languages but more generally you get subject specific tutorials on
things like parsing, web programming, GUI programming, databases,
networking, stats and scientific programming etc etc.

So there are usually intermediate level tutorials to suit they are 
rarely

full language tutorials.

I try to cover that off with the advanced topics and "Python in 
practice"
topics at the end of my tutorial. But again they are focused on 
specific

topic areas (OS, database, networks, web).

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] 'Installing' Python at runtime? (Civilization)

2011-02-03 Thread C.Y. Ruhulessin
Hi all,

When I load up Civilization IV, a Firaxis game, the loading screen tells me
"Loading Python".

However, I can't seem to find out where it installs python (and Python
wasn't installed before I installed it myself), so I *assume *that it
'installs' and loads Python at runtime.

For an application that I am designing, i'd like to achieve the same
functionality, so the end users don't have to bother installing Python
themselves.

Can anybody shed their lights on how one would program this?

kind regards,

Izz ad-Din
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] RE module is working ?

2011-02-03 Thread Karim


Hello Steven,

I am perhaps a poor tradesman but I have to blame my thunderbird tool :-P .
Because expression = *' "" '*  is in fact fact expression = ' "" '.
The bold appear as stars I don't know why. I need to have escapes for 
passing it to another language (TCL interpreter).

So I will rewrite it not _in bold_:

$ python
Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> expression = ' "" '

>>> re.subn(r'([^\\])?"', r'\1\\"', expression)

But if I remove '?' I get the following:

>>> re.subn(r'([^\\])"', r'\1\\"', expression)
(' \\"" ', 1)

   * On linux using my good old sed command, it is working with my '?'
 (0-1 match):

$ echo ' "" ' | sed 's/\([^\\]\)\?"/\1\\"/g'*
* \"\"

For me linux/unix sed utility is trusty and is the reference.

Regards
Karim


On 02/03/2011 11:43 AM, Steven D'Aprano wrote:

Karim wrote:


Hello,

I am trying to subsitute a '""' pattern in '\"\"' namely escape 2 
consecutives double quotes:


You don't have to escape quotes. Just use the other sort of quote:

>>> print '""'
""



   * *In Python interpreter:*

$ python
Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> expression = *' "" '*


No, I'm sorry, that's incorrect -- that gives a syntax error in every 
version of Python I know of, including version 2.7:


>>> expression = *' "" '*
  File "", line 1
expression = *' "" '*
 ^
SyntaxError: invalid syntax


So what are you really running?




>>> re.subn(*r'([^\\])?"', r'\1\\"', expression*)


Likewise here. *r'...' is a syntax error, as is expression*)

I don't understand what you are running or why you are getting the 
results you are.



> *Indeed what's the matter with RE module!?*

There are asterisks all over your post! Where are they coming from?

What makes you think the problem is with the RE module?

We have a saying in English:

"The poor tradesman blames his tools."

Don't you think it's more likely that the problem is that you are 
using the module wrongly?


I don't understand what you are trying to do, so I can't tell you how 
to do it. Can you give an example of what you want to start with, and 
what you want to end up with? NOT Python code, just literal text, like 
you would type into a letter.


E.g. ABC means literally A followed by B followed by C.
\" means literally backslash followed by double-quote






___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 'Installing' Python at runtime? (Civilization)

2011-02-03 Thread Noah Hall
On Thu, Feb 3, 2011 at 11:11 AM, C.Y. Ruhulessin
 wrote:
> For an application that I am designing, i'd like to achieve the same
> functionality, so the end users don't have to bother installing Python
> themselves.
> Can anybody shed their lights on how one would program this?
> kind regards,


There are applications, such as http://www.py2exe.org/ and
http://www.pyinstaller.org/ that you can use to achieve the same
thing.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] RE module is working ?

2011-02-03 Thread Karim


I forget something. There is no issue with python and double quotes.
But I need to give it to TCL script but as TCL is shit string is only 
delimited by double quotes.
Thus I need to escape it to not have syntax error whith nested double 
quotes.


Regards
The poor tradesman


On 02/03/2011 12:45 PM, Karim wrote:


Hello Steven,

I am perhaps a poor tradesman but I have to blame my thunderbird tool 
:-P .

Because expression = *' "" '*  is in fact fact expression = ' "" '.
The bold appear as stars I don't know why. I need to have escapes for 
passing it to another language (TCL interpreter).

So I will rewrite it not _in bold_:

$ python
Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> expression = ' "" '

>>> re.subn(r'([^\\])?"', r'\1\\"', expression)

But if I remove '?' I get the following:

>>> re.subn(r'([^\\])"', r'\1\\"', expression)
(' \\"" ', 1)

* On linux using my good old sed command, it is working with my
  '?' (0-1 match):

$ echo ' "" ' | sed 's/\([^\\]\)\?"/\1\\"/g'*
* \"\"

For me linux/unix sed utility is trusty and is the reference.

Regards
Karim


On 02/03/2011 11:43 AM, Steven D'Aprano wrote:

Karim wrote:


Hello,

I am trying to subsitute a '""' pattern in '\"\"' namely escape 2 
consecutives double quotes:


You don't have to escape quotes. Just use the other sort of quote:

>>> print '""'
""



   * *In Python interpreter:*

$ python
Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> expression = *' "" '*


No, I'm sorry, that's incorrect -- that gives a syntax error in every 
version of Python I know of, including version 2.7:


>>> expression = *' "" '*
  File "", line 1
expression = *' "" '*
 ^
SyntaxError: invalid syntax


So what are you really running?




>>> re.subn(*r'([^\\])?"', r'\1\\"', expression*)


Likewise here. *r'...' is a syntax error, as is expression*)

I don't understand what you are running or why you are getting the 
results you are.



> *Indeed what's the matter with RE module!?*

There are asterisks all over your post! Where are they coming from?

What makes you think the problem is with the RE module?

We have a saying in English:

"The poor tradesman blames his tools."

Don't you think it's more likely that the problem is that you are 
using the module wrongly?


I don't understand what you are trying to do, so I can't tell you how 
to do it. Can you give an example of what you want to start with, and 
what you want to end up with? NOT Python code, just literal text, 
like you would type into a letter.


E.g. ABC means literally A followed by B followed by C.
\" means literally backslash followed by double-quote







___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 'Installing' Python at runtime? (Civilization)

2011-02-03 Thread C.Y. Ruhulessin
Thanks, will check it out!

2011/2/3 Noah Hall 

> On Thu, Feb 3, 2011 at 11:11 AM, C.Y. Ruhulessin
>  wrote:
> > For an application that I am designing, i'd like to achieve the same
> > functionality, so the end users don't have to bother installing Python
> > themselves.
> > Can anybody shed their lights on how one would program this?
> > kind regards,
>
>
> There are applications, such as http://www.py2exe.org/ and
> http://www.pyinstaller.org/ that you can use to achieve the same
> thing.
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] RE module is working ?

2011-02-03 Thread Peter Otten
Karim wrote:

> I am trying to subsitute a '""' pattern in '\"\"' namely escape 2
> consecutives double quotes:
> 
> * *In Python interpreter:*
> 
> $ python
> Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40)
> [GCC 4.4.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> expression = *' "" '*
>  >>> re.subn(*r'([^\\])?"', r'\1\\"', expression*)
> Traceback (most recent call last):
>File "", line 1, in 
>File "/home/karim/build/python/install/lib/python2.7/re.py", line
> 162, in subn
>  return _compile(pattern, flags).subn(repl, string, count)
>File "/home/karim/build/python/install/lib/python2.7/re.py", line
> 278, in filter
>  return sre_parse.expand_template(template, match)
>File "/home/karim/build/python/install/lib/python2.7/sre_parse.py",
> line 787, in expand_template
>  raise error, "unmatched group"
> sre_constants.error: unmatched group
> 
> But if I remove '?' I get the following:
> 
>  >>> re.subn(r'([^\\])"', r'\1\\"', expression)
> (' \\"" ', 1)
> 
> Only one substitution..._But this is not the same REGEX._ And the
> count=2 does nothing. By default all occurrence shoul be substituted.
> 
> * *On linux using my good old sed command, it is working with my '?'
>   (0-1 match):*
> 
> *$* echo *' "" '* | sed *'s/\([^\\]\)\?"/\1\\"/g*'*
>   \"\"
> 
> *Indeed what's the matter with RE module!?*

You should really fix the problem with your email program first; afterwards 
it's probably a good idea to try and explain your goal clearly, in plain 
English.

Yes. What Steven said ;)

Now to your question as stated: if you want to escape two consecutive double 
quotes that can be done with

s = s.replace('""', '\"\"')

but that's probably *not* what you want. Assuming you want to escape two 
consecutive double quotes and make sure that the first one isn't already 
escaped, this is my attempt:

>>> def sub(m):
... s = m.group()
... return r'\"\"' if s == '""' else s
...
>>> print re.compile(r'[\\].|""').sub(sub, r'\\\"" \\"" \"" "" \\\" \\" \"')
\\\"" \\\"\" \"" \"\" \\\" \\" \"

Compare that with

$ echo '\\\"" \\"" \"" "" \\\" \\" \"' | sed 's/\([^\\]\)\?"/\1\\"/g'
\\\"\" \\"\" \"\" \"\" " \\\" \\"

Concerning the exception and the discrepancy between sed and python's re, I 
suggest that you ask it again on comp.lang.python aka the python-list 
mailing list where at least one regex guru will read it.

Peter

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] question about locale.setlocale

2011-02-03 Thread Rafael Durán Castañeda
Hi all,

I'm new in Python, so I'm reading 3.1 tutorial and now I've got a question
about locale.setlocale function. I've tryed in python idle this:

import locale

locale.setlocale(locale.LC_ALL, 'English_United States.1252')

and i got:

Traceback (most recent call last):
  File "", line 1, in 
locale.setlocale(locale.LC_ALL,'English_United States.1252')
  File "/usr/lib/python3.1/locale.py", line 527, in setlocale
return _setlocale(category, locale)
locale.Error: unsupported locale setting

After that I checked locale.py trying to know which locale settings are
supported I found:

def setlocale(category, value=None):
""" setlocale(integer,string=None) -> string.
Activates/queries locale processing.
"""
if value not in (None, '', 'C'):
raise Error('_locale emulation only supports "C" locale')
return 'C'

So here I can use only default (es_ES.utf8) and C locales, but how can I use
any other locale?

Bye
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Defining Exceptions

2011-02-03 Thread Emile van Sebille

Hi Tom,

First, you sent this only to me -- be sure to reply all so that the 
group can participate.


On 2/2/2011 10:25 AM Tom Brauch said...
> Thanks, Emile.
>
> If I replace the question marks in my script with break it throws out
> everything before the break (<) and gives me the header starting at 4 -
> Display.
>
> Knowing that it works to that point I was hoping to be able to tell the
> script to throw out everything before the "T," at the end of the 
header in

> which case I get only the data.
>
> How do I define "T," so that python recognizes it?  Is it an iteration?


You need to understand the structures you're working with.  lines is a 
list that you created with "lines = resp.split('\r\n')" -- add a line 
immediately after this that reads : "for ii in lines: print ii" (or 
print(ii) if you're on v3+  are you?) -- that'll show you what you've 
got.  Paste the results in your reply.  If the line you're interested in 
literally is the only one that has ',T,' in it, you could keep the part 
after that more easily with something like:


...
ser.write('3')
resp=buffer_read(ser)
waste,goodlines = resp.split(",T,")
...

and go from there using goodlines.


HTH,

Emile



>
> Sorry I can't ask more intelligent questions but I'm truly just getting
> started.
>
> Thanks again!
> Tom
>
>
> On Wed, Feb 2, 2011 at 10:58 AM, Emile van Sebille  
wrote:

>
>> On 2/2/2011 6:51 AM Tom Brauch said...
>>
>>  All,
>>>
>>> I am a python neophyte and not terrible well versed in programming (as
>>> will
>>> become obvious shortly)
>>>
>>> I have a script which is reading a serial device on a schedule.  The
>>> device
>>> outputs a header at the beginning of every read.  I have a data 
file which

>>> I
>>> am appending and would like to eliminate the header so that I end 
up with

>>> one master data file.  A copy of the serial readout is:
>>>
>>> *
>>>

  6CSV Type Reports2 - Display All Data3 - Display New Data4 - Display
>>> Last
>>> Data5 - Display All Flow Stats6 - Display New Flow Stats7 - Display All
>>> 5-Min Flow8 - Display New 5-Min Flow9 - Display Error Log>
>>> 4 - Display CSV DataStation,
>>>
>>> 
1Time,Conc(mg/m3),Qtot(m3),no(V),WS(MPS),no(V),RH(%),no(V),AT(C),E,U,M,I,L,R,N,F,P,D,C,T,02/02/11

>>> 08:00,  0.042, 0.701, 0.004,   0.1, 0.002, 7, 0.012,
>>> -18.0,0,0,0,0,0,0,0,0,0,0,0,0,
>>>
>>> I am only interested in the information following the T, in the 
header.  I
>>> have tried to use an exception to have the script throw out all 
data prior

>>> to the T, in the header but I don't know how to define this excecption.
>>>  My
>>> current script looks as follows:
>>>
>>> def cycle(ser,prefix):
>>> inRecovery=False
>>> resp=False
>>> #tm.sleep(30.0)
>>> ser.open()
>>> tm.sleep(2)
>>> ser.write('\n\r\n\r\n\r')
>>> resp=buffer_read(ser)
>>>
>>> ser.write('6')
>>> resp=buffer_read(ser)
>>>
>>> ser.write('3')
>>> resp=buffer_read(ser)
>>> lines = resp.split('\r\n')
>>> waste=lines.pop()
>>>
>>
>> pop changes lines by discarding the end of the list.  So your subsequent
>> remove fails because waste is no longer in the list.
>>
>> Perhaps waste is the data you're looking for?
>>
>> sprinkle some prints through here so you can see what values you're 
dealing

>> with.  That's a common technique to help figure out what's wrong.
>>
>> HTH,
>>
>> Emile
>>
>>
>>  while True:
>>> try:
>>> lines.remove(waste)
>>> except Exception:
>>> ??
>>> for x,row in enumerate(lines):
>>> lines[x]=row.split(',')
>>> if DEBUG: print lines
>>> f=open(prefix,'a')
>>> csvf = csv.writer(f)
>>> csvf.writerows(lines)
>>> f.close()
>>> ser.close()
>>>
>>> How do I define the exception so that I get only the data following the
>>> header?
>>>
>>> Thanks!
>>> Tomb
>>>
>>>

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] print "Hello, World!"

2011-02-03 Thread Doug Marvel
Holy wow! I'm going to go through all of these and see what sort of
understanding I can absorb. I'm super excited that a helpful community
exists for this, but I'm more excited to start learning. So I'm going
to go do that now. I'm starting with Alan Gauld's tutorial, but like I
said, I'm going to check out all of them, until I build some
confidence. So far, this one seems to run at my speed. I'll be back,
for certain. It took me twenty minutes to figure out how to get the
">>>" to come up in DOS after typing 'python'. hahaha


It's good to meet all of you, and thanks again.
Doug

On Thu, Feb 3, 2011 at 6:07 AM, Alan Gauld  wrote:
> "michael scott"  wrote
>
>> already been asked, learn from others who asked before you :) Oh yea, I
>> once
>> read that there are no intermediate tutorials in any programming language,
>> because once you get past the basics, you only need to reference the
>> "documentation" that comes with the language.
>
> Thats very nearly true. There are intermediate level tutorials for a few
> languages but more generally you get subject specific tutorials on
> things like parsing, web programming, GUI programming, databases,
> networking, stats and scientific programming etc etc.
>
> So there are usually intermediate level tutorials to suit they are rarely
> full language tutorials.
>
> I try to cover that off with the advanced topics and "Python in practice"
> topics at the end of my tutorial. But again they are focused on specific
> topic areas (OS, database, networks, web).
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Changing Python icon - 2.6 and 3.2

2011-02-03 Thread Patty
Hello Folks - I have Python 2.6.6 on my Windows 7 system and installed Python 
3.2.  Now I want to be able to differentiate between the versions and the icon 
for each version of Python is the same.  I figured I would change the the four 
application files in the C:\Python26 directory - python; python26; pythonw; 
pythonw26 - and give them new picture icons.  But when I select any of these 
files and choose 'properties', there is no option to change the application 
icon.  I looked online but the questions were not exactly the same as this one 
and pertained to earlier versions of Python anyway.  I discovered this when I 
was trying to associate a folder with 2.6 based programs so that it would 
always execute the programs with the python 2.6 .exe.  And both Pythons come up 
as a choice with no details indicating which is which, except a lucky guess.

It does appear that I can change the actual name of the application (the field 
with the name allows me to edit) but that is not what I wanted to do, also 
unsure if that would cause a problem in other parts of the application down the 
road if I was changing names like that.  

Thanks for suggestions -

Patty___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Changing Python icon - 2.6 and 3.2

2011-02-03 Thread Bill Felton
I haven't tried this on Windows 7 yet, but what I did on my Mac was to create 
shortcuts and rename those.  I generally launch from shortcuts, so this leaves 
the app names alone but gives me the information I need to launch what I 
intend.  You should be able to do something similar on Windows.

regards,
Bill

On Feb 3, 2011, at 12:18 PM, Patty wrote:

> Hello Folks - I have Python 2.6.6 on my Windows 7 system and installed Python 
> 3.2.  Now I want to be able to differentiate between the versions and the 
> icon for each version of Python is the same.  I figured I would change the 
> the four application files in the C:\Python26 directory - python; python26; 
> pythonw; pythonw26 - and give them new picture icons.  But when I select any 
> of these files and choose 'properties', there is no option to change the 
> application icon.  I looked online but the questions were not exactly the 
> same as this one and pertained to earlier versions of Python anyway.  I 
> discovered this when I was trying to associate a folder with 2.6 based 
> programs so that it would always execute the programs with the python 2.6 
> .exe.  And both Pythons come up as a choice with no details indicating which 
> is which, except a lucky guess.
>  
> It does appear that I can change the actual name of the application (the 
> field with the name allows me to edit) but that is not what I wanted to do, 
> also unsure if that would cause a problem in other parts of the application 
> down the road if I was changing names like that. 
>  
> Thanks for suggestions -
> Patty
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] print "Hello, World!"

2011-02-03 Thread Patty
Hello Doug - My very first document I read - before I took an online 
course - was "A Quick, Painless Tutorial on the Python Language" by Norman 
Matloff from UC Davis.  My copy is dated May 1, 2009 but I think he has 
updated it -- looks like May 2010.  Here is the link, you may also want to 
query for other links like this for Matloff because I saw a few others while 
looking this up for you.  It is free.


http://html-pdf-converter.com/pdf/a-quick-painless-tutorial-on-the-python-language.html

I also liked Alan Gauld's tutorial and the videos made by Google - taught by 
Nick Parlante - Here is the link:


http://code.google.com/edu/languages/google-python-class/

I was not really happy with the actual course I took.  You can contact me 
offline about this.


Regards,

Patty


- Original Message - 
From: "Doug Marvel" 

To: ; 
Sent: Thursday, February 03, 2011 7:28 AM
Subject: Re: [Tutor] print "Hello, World!"


Holy wow! I'm going to go through all of these and see what sort of
understanding I can absorb. I'm super excited that a helpful community
exists for this, but I'm more excited to start learning. So I'm going
to go do that now. I'm starting with Alan Gauld's tutorial, but like I
said, I'm going to check out all of them, until I build some
confidence. So far, this one seems to run at my speed. I'll be back,
for certain. It took me twenty minutes to figure out how to get the
">>>" to come up in DOS after typing 'python'. hahaha


It's good to meet all of you, and thanks again.
Doug

On Thu, Feb 3, 2011 at 6:07 AM, Alan Gauld  
wrote:

"michael scott"  wrote


already been asked, learn from others who asked before you :) Oh yea, I
once
read that there are no intermediate tutorials in any programming 
language,

because once you get past the basics, you only need to reference the
"documentation" that comes with the language.


Thats very nearly true. There are intermediate level tutorials for a few
languages but more generally you get subject specific tutorials on
things like parsing, web programming, GUI programming, databases,
networking, stats and scientific programming etc etc.

So there are usually intermediate level tutorials to suit they are rarely
full language tutorials.

I try to cover that off with the advanced topics and "Python in practice"
topics at the end of my tutorial. But again they are focused on specific
topic areas (OS, database, networks, web).

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Changing Python icon - 2.6 and 3.2

2011-02-03 Thread Marc Tompkins
On Thu, Feb 3, 2011 at 9:18 AM, Patty  wrote:

>  Hello Folks - I have Python 2.6.6 on my Windows 7 system and installed
> Python 3.2.  Now I want to be able to differentiate between the versions and
> the icon for each version of Python is the same.  I figured I would change
> the the four application files in the C:\Python26 directory - python;
> python26; pythonw; pythonw26 - and give them new picture icons.  But when
> I select any of these files and choose 'properties', there is no option to
> change the application icon.  I looked online but the questions were not
> exactly the same as this one and pertained to earlier versions of Python
> anyway.  I discovered this when I was trying to associate a folder with 2.6
> based programs so that it would always execute the programs with the python
> 2.6 .exe.  And both Pythons come up as a choice with no details indicating
> which is which, except a lucky guess.
>
> It does appear that I can change the actual name of the application (the
> field with the name allows me to edit) but that is not what I wanted to do,
> also unsure if that would cause a problem in other parts of the application
> down the road if I was changing names like that.
>

Windows EXEs are generally built with one or more icon images packaged
inside them; at build time, the developer chooses which one s/he wants to be
the regular display icon.  As an end user, you generally cannot choose which
of the built-in images Windows will choose to display when you look at the
EXE in a directory listing - Windows sticks with the developer's choice.

However, when you create a shortcut - or modify one that's already been
created - you have free choice of which icon you want to use.  Typically
when you click the "Change Icon" button, you'll see the icons that are
contained in the EXE itself, but you can choose any other icon image file on
your computer - even icons that are contained in completely different EXEs.

Unfortunately, none of that helps with what you're trying to do.  You want
to change the name/description that was registered with Default Programs
when your versions of Python were installed... and as near as I can tell,
the Python installers don't "register" with Default Programs at all.
("Default Programs" is the Vista/7/Longhorn version of... whatever you call
this mess.)  When an installer doesn't provide the information for
registration, Windows defaults to the executable name (which is "python.exe"
in both cases) and the executable's default icon (which, as you've noticed,
hasn't changed between versions either.)

This page describes the registry keys that could/should be set:

http://msdn.microsoft.com/en-us/library/cc144154%28v=vs.85%29.aspx#post_install
but I don't know whether messing with them by hand is likely to be either
safe or effective.

However, one thing you CAN do is to create shortcuts for the actual .py or
.pyw files themselves, and in the shortcut's command line specify the path
to the Python executable you want to use (e.g. "C:\Python26\pythonw.exe
C:\Users\Patty\Desktop\PythonProj26\myprog.py".)  If we're talking about
just a few files, that could be doable.  For more than about a dozen, it
would be an unbelievable pain.
-- 
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] RE module is working ?

2011-02-03 Thread Karim

On 02/03/2011 02:15 PM, Peter Otten wrote:

Karim wrote:


I am trying to subsitute a '""' pattern in '\"\"' namely escape 2
consecutives double quotes:

 * *In Python interpreter:*

$ python
Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
  >>>  expression = *' "" '*
  >>>  re.subn(*r'([^\\])?"', r'\1\\"', expression*)
Traceback (most recent call last):
File "", line 1, in
File "/home/karim/build/python/install/lib/python2.7/re.py", line
162, in subn
  return _compile(pattern, flags).subn(repl, string, count)
File "/home/karim/build/python/install/lib/python2.7/re.py", line
278, in filter
  return sre_parse.expand_template(template, match)
File "/home/karim/build/python/install/lib/python2.7/sre_parse.py",
line 787, in expand_template
  raise error, "unmatched group"
sre_constants.error: unmatched group

But if I remove '?' I get the following:

  >>>  re.subn(r'([^\\])"', r'\1\\"', expression)
(' \\"" ', 1)

Only one substitution..._But this is not the same REGEX._ And the
count=2 does nothing. By default all occurrence shoul be substituted.

 * *On linux using my good old sed command, it is working with my '?'
   (0-1 match):*

*$* echo *' "" '* | sed *'s/\([^\\]\)\?"/\1\\"/g*'*
   \"\"

*Indeed what's the matter with RE module!?*

You should really fix the problem with your email program first;
Thunderbird issue with bold type (appears as stars) but I don't know how 
to fix it yet.

  afterwards
it's probably a good idea to try and explain your goal clearly, in plain
English.


I already did it. (cf the mails queue). But to resume I pass the 
expression string to TCL command which delimits string with double 
quotes only.

Indeed I get error with nested double quotes => That's the key problem.

Yes. What Steven said ;)

Now to your question as stated: if you want to escape two consecutive double
quotes that can be done with

s = s.replace('""', '\"\"')

I have already done it as a workaround but I have to add another 
replacement before to consider all other cases.

I want to make the original command work to suppress the workaround.



but that's probably *not* what you want. Assuming you want to escape two
consecutive double quotes and make sure that the first one isn't already
escaped,


You hit it !:-)


this is my attempt:


def sub(m):

... s = m.group()
... return r'\"\"' if s == '""' else s
...

print re.compile(r'[\\].|""').sub(sub, r'\\\"" \\"" \"" "" \\\" \\" \"')


That is not the thing I want. I want to escape any " which are not 
already escaped.
The sed regex  '/\([^\\]\)\?"/\1\\"/g' is exactly what I need (I have 
made regex on unix since 15 years).


For me the equivalent python regex is buggy: r'([^\\])?"', r'\1\\"'
'?' is not accepted Why? character which should not be an antislash with 
0 or 1 occurence. This is quite simple.


I am a poor tradesman but I don't deny evidence.

Regards
Karim


\\\"" \\\"\" \"" \"\" \\\" \\" \"

Compare that with

$ echo '\\\"" \\"" \"" "" \\\" \\" \"' | sed 's/\([^\\]\)\?"/\1\\"/g'
\\\"\" \\"\" \"\" \"\" " \\\" \\"

Concerning the exception and the discrepancy between sed and python's re, I
suggest that you ask it again on comp.lang.python aka the python-list
mailing list where at least one regex guru will read it.

Peter

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Ideas and good examples

2011-02-03 Thread David Goering

Hello,
this is my first message here... and come to think of it my first 
Message in a Mailing List what so ever. So a moment of epic historical 
importance :)
Anyway I decided I wanted to learn Python as I didn't really know any 
scripting language yet and I have heard great things about Python.
I already have some experience in Java and minor experience in C 
languages... so I think I will pick up on the syntax pretty quickly 
(just have to get used to not using braces and indent my code correctly :D )
Anyhow my programming knowledge is based off classes and less off of 
practically using them a lot... So I have implemented various algorithms 
etc. but haven't written many full programs from beginning to end.
And that is basically my question / problem. I don't have many good 
ideas and I don't really have a lot of experience with going from an 
idea to a full scale program.

So I guess I have two questions:
1) Does anyone have ideas for small - mid ranged projects where I could 
quickly pick up on the pitfalls of Python but that is also useful in 
some way ? I had a small idea where I could write a program to sync two 
folders mp3 files based on filename and ID3 Tags with a GUI to control 
it, but would love to hear other ideas.
2) Is there some tutorial out there that really leads you from scratch 
to a full blown program (with GUI or Database connection or whatever) 
with Code documentation etc. just to see how one could approach it
Anyway, I have already learned a lot from leeching off the mailing list, 
so thanks for that.

Greetings from Germany,
David
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Namespace variables vs. instantiation keywords - best practices

2011-02-03 Thread Tim Johnson
FYI: Python 2.6.5 on Linux.
FYI: I am a web programmer of 24 years experience programming, 9
with python, but have never had the advantage of working with a
senior programmer as a mentor. I am investigating the best practices
of instantiating an object with a large amount of options. I would
also request that when the reader sees me using terminology that is
not pythonic that I be corrected. That will help me to better
communicate my practices and researching this topic via search
engines.

I'm redesigning a large system to an MVC architecture. 
To make a long story short, I and clients have chosen *not* to adapt
this system to an existing framework such as django, but to develop
and original framework with an eye towards integrating with
something like django in the future.

# Bootstrapping:
An executable script imports a 'site module' that sets up a
project-specific environment. 

# Managing content
I have developed a view (template) module for which most of the
heavy lifting is done. 

The interface to the class looks like this:
def __init__(self,**kw):
## Consider that all code examples are pseudo-code
"""
 tmpl.py
 Purpose - python templating features
 Author - Me - m...@mydomain.com
"""
## I will use two public module variables as an example:
## default variables in the module namespace
templatepath = "templates" ## default value
projectname = ""   ## must be intialized 

## Object variables in the class namespace
## Initialized from the public module variables
self.templatepath = templatepath 
self.prj = projectname

## Intialization loop. Defaults can be 'overridden'
for k in kw:
if k in self.__dict__:
self.__dict__[k] = kw[k]
else : ## raise exception

#instantiation code might look like this:
content = LoadView(prj="myproject",templatepath="views")

# or 
kws = {"prj":"myproject","templatepath":"views"}
content = LoadView(**kws)

# OR (project config file)
kws = load.config("myconfig","tmpl_kws")
kws.update({"prj":"myproject","templatepath":"views"})
kws = {"prj":"myproject","templatepath":"views"}

# OR - use the site module - example site module code follows:
## Import the module containing the `LoadView' class
import tmpl
## set the module namespace variables.
tmpl.projectname = MyProject
tmpl.templatepath = TemplatePath
## Calling module settings follow.

I've received some very helpful comments in the past by senior
members of this ML and perhaps this topic may help other as
well as myself
TIA
-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Ideas and good examples

2011-02-03 Thread Tino Dai
On Thu, Feb 3, 2011 at 2:24 PM, David Goering  wrote:

> Hello,
> this is my first message here... and come to think of it my first Message
> in a Mailing List what so ever. So a moment of epic historical importance :)
> Anyway I decided I wanted to learn Python as I didn't really know any
> scripting language yet and I have heard great things about Python.
> I already have some experience in Java and minor experience in C
> languages... so I think I will pick up on the syntax pretty quickly (just
> have to get used to not using braces and indent my code correctly :D )
> Anyhow my programming knowledge is based off classes and less off of
> practically using them a lot... So I have implemented various algorithms
> etc. but haven't written many full programs from beginning to end.
> And that is basically my question / problem. I don't have many good ideas
> and I don't really have a lot of experience with going from an idea to a
> full scale program.
> So I guess I have two questions:
> 1) Does anyone have ideas for small - mid ranged projects where I could
> quickly pick up on the pitfalls of Python but that is also useful in some
> way ? I had a small idea where I could write a program to sync two folders
> mp3 files based on filename and ID3 Tags with a GUI to control it, but would
> love to hear other ideas.
>

Start reading Dive into Python http://diveintopython.org/ . He has an
example like that


> 2) Is there some tutorial out there that really leads you from scratch to a
> full blown program (with GUI or Database connection or whatever) with Code
> documentation etc. just to see how one could approach it
>

Start with TKinter or a framework like Django. Please note that Django is
out of scope for this list, but there are plenty of good resources out on
the net.

Finally you should check out Alan Gauld's page:
http://www.freenetpages.co.uk/hp/alan.gauld/  and Kent Johnson page:
http://personalpages.tds.net/~kent37/blog/


Welcome!
Tino
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Namespace variables vs. instantiation keywords - best practices

2011-02-03 Thread Tim Johnson
* Tim Johnson  [110203 10:34]:
> # OR (project config file)
> kws = load.config("myconfig","tmpl_kws")
> kws.update({"prj":"myproject","templatepath":"views"})
#Grr! The following line is wrong ..
> kws = {"prj":"myproject","templatepath":"views"}
Should be
#content = LoadView(**kws)
sorry
-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] RE module is working ?

2011-02-03 Thread Dave Angel

On 01/-10/-28163 02:59 PM, Karim wrote:

On 02/03/2011 02:15 PM, Peter Otten wrote:

Karim wrote:
  (snip>

*Indeed what's the matter with RE module!?*

You should really fix the problem with your email program first;

Thunderbird issue with bold type (appears as stars) but I don't know how
to fix it yet.


The simple fix is not to try to add bold or colors on a text message. 
Python-tutor is a text list, not an html one.  Thunderbird tries to 
accomodate you by adding the asterisks, which is fine if it's regular 
English.  But in program code, it's obviously confuses things.


While I've got you, can I urge you not to top-post?  In this message, 
you correctly added your remarks after the part you were quoting.  But 
many times you put your comments at the top, which is backwards.


DaveA

--
--
da...@ieee.org
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] RE module is working ?

2011-02-03 Thread Karim

On 02/03/2011 11:20 PM, Dave Angel wrote:

On 01/-10/-28163 02:59 PM, Karim wrote:

On 02/03/2011 02:15 PM, Peter Otten wrote:

Karim wrote:
  (snip>

*Indeed what's the matter with RE module!?*

You should really fix the problem with your email program first;

Thunderbird issue with bold type (appears as stars) but I don't know how
to fix it yet.


The simple fix is not to try to add bold or colors on a text message. 
Python-tutor is a text list, not an html one.  Thunderbird tries to 
accomodate you by adding the asterisks, which is fine if it's regular 
English.  But in program code, it's obviously confuses things.


While I've got you, can I urge you not to top-post?  In this message, 
you correctly added your remarks after the part you were quoting.  But 
many times you put your comments at the top, which is backwards.


DaveA



Sorry Dave,

I will try and do my best to avoid bold and top-post in the future.

Regards
Karim
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] RE module is working ?

2011-02-03 Thread Karim

On 02/03/2011 07:47 PM, Karim wrote:

On 02/03/2011 02:15 PM, Peter Otten wrote:

Karim wrote:


I am trying to subsitute a '""' pattern in '\"\"' namely escape 2
consecutives double quotes:

 * *In Python interpreter:*

$ python
Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>  expression = *' "" '*
>>>  re.subn(*r'([^\\])?"', r'\1\\"', expression*)
Traceback (most recent call last):
File "", line 1, in
File "/home/karim/build/python/install/lib/python2.7/re.py", line
162, in subn
  return _compile(pattern, flags).subn(repl, string, count)
File "/home/karim/build/python/install/lib/python2.7/re.py", line
278, in filter
  return sre_parse.expand_template(template, match)
File "/home/karim/build/python/install/lib/python2.7/sre_parse.py",
line 787, in expand_template
  raise error, "unmatched group"
sre_constants.error: unmatched group

But if I remove '?' I get the following:

>>>  re.subn(r'([^\\])"', r'\1\\"', expression)
(' \\"" ', 1)

Only one substitution..._But this is not the same REGEX._ And the
count=2 does nothing. By default all occurrence shoul be substituted.

 * *On linux using my good old sed command, it is working with 
my '?'

   (0-1 match):*

*$* echo *' "" '* | sed *'s/\([^\\]\)\?"/\1\\"/g*'*
   \"\"

*Indeed what's the matter with RE module!?*

You should really fix the problem with your email program first;
Thunderbird issue with bold type (appears as stars) but I don't know 
how to fix it yet.

  afterwards
it's probably a good idea to try and explain your goal clearly, in plain
English.


I already did it. (cf the mails queue). But to resume I pass the 
expression string to TCL command which delimits string with double 
quotes only.

Indeed I get error with nested double quotes => That's the key problem.

Yes. What Steven said ;)

Now to your question as stated: if you want to escape two consecutive 
double

quotes that can be done with

s = s.replace('""', '\"\"')

I have already done it as a workaround but I have to add another 
replacement before to consider all other cases.

I want to make the original command work to suppress the workaround.



but that's probably *not* what you want. Assuming you want to escape two
consecutive double quotes and make sure that the first one isn't already
escaped,


You hit it !:-)


this is my attempt:


def sub(m):

... s = m.group()
... return r'\"\"' if s == '""' else s
...
print re.compile(r'[\\].|""').sub(sub, r'\\\"" \\"" \"" "" \\\" 
\\" \"')


That is not the thing I want. I want to escape any " which are not 
already escaped.
The sed regex  '/\([^\\]\)\?"/\1\\"/g' is exactly what I need (I have 
made regex on unix since 15 years).


For me the equivalent python regex is buggy: r'([^\\])?"', r'\1\\"'
'?' is not accepted Why? character which should not be an antislash 
with 0 or 1 occurence. This is quite simple.


I am a poor tradesman but I don't deny evidence.


Recall:

>>> re.subn(r'([^\\])?"', r'\1\\"', expression)

Traceback (most recent call last):
File "", line 1, in
File "/home/karim/build/python/install/lib/python2.7/re.py", line
162, in subn
  return _compile(pattern, flags).subn(repl, string, count)
File "/home/karim/build/python/install/lib/python2.7/re.py", line
278, in filter
  return sre_parse.expand_template(template, match)
File "/home/karim/build/python/install/lib/python2.7/sre_parse.py",
line 787, in expand_template
  raise error, "unmatched group"
sre_constants.error: unmatched group


Found the solution: '?' needs to be inside parenthesis (saved pattern) 
because outside we don't know if the saved match argument

will exist or not namely '\1'.

>>> re.subn(r'([^\\]?)"', r'\1\\"', expression)

(' \\"\\" ', 2)

sed unix command is more permissive: sed 's/\([^\\]\)\?"/\1\\"/g' 
because '?' can be outside parenthesis (saved pattern but escaped for sed).
\1 seems to not cause issue when matching is found. Perhaps it is 
created only when match occurs.


MORALITY:

1) Behaviour of python is logic and I must understand what I do with it.
2) sed is a fantastic tool because it manages match value when missing.
3) I am a real poor tradesman

Regards
Karim



Regards
Karim


\\\"" \\\"\" \"" \"\" \\\" \\" \"

Compare that with

$ echo '\\\"" \\"" \"" "" \\\" \\" \"' | sed 's/\([^\\]\)\?"/\1\\"/g'
\\\"\" \\"\" \"\" \"\" " \\\" \\"

Concerning the exception and the discrepancy between sed and python's 
re, I

suggest that you ask it again on comp.lang.python aka the python-list
mailing list where at least one regex guru will read it.

Peter

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:

Re: [Tutor] RE module is working ?

2011-02-03 Thread Alan Gauld


"Karim"  wrote


Because expression = *' "" '*  is in fact fact expression = ' "" '.
The bold appear as stars I don't know why. 


Because in the days when email was always sent in plain 
ASCII text the way to show "bold" was to put asterisks around 
it. Underlining used _underscores_ like so...


Obviously somebody decided that Thunderbird would stick 
with those conventions when translating HTML to text :-)


Quite smart really :-)

Alan G.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] System of ODEs Question

2011-02-03 Thread Eike Welk
Hello Eric!


On Thursday 03.02.2011 08:05:13 Eric Lofgren wrote:

> def eq_system(PopIn,x):
> '''Defining SIR System of Equations'''
> #Creating an array of equations
> Eqs= np.zeros((3))
> Eqs[0]= -beta * PopIn[0]*PopIn[1]
> Eqs[1]= beta * PopIn[0]*PopIn[1] - gamma*PopIn[1]
> Eqs[2]= gamma*PopIn[1]
> return Eqs
> 
> SIR = spi.odeint(eq_system, PopIn, t_interval)
> print SIR

> The part that is confusing me is defining the function. Namely, it seems to
> need two arguments - the first needs to be the initial states of the
> population being modeled, but the second...it doesn't seem to matter what
> it is. Originally, I didn't include it at all, and the program was very,
> very unhappy - looking back at the example, it had a second argument, so I
> put one in, and magically, it worked. But it can be x, it can be t, it can
> be anything.

The meaning of the arguments of the system function (`eq_system` in your code) 
is as follows:

1. (`PopIn` in your code) the current state of the system
2. (`x` in your code) the current time

The arguments can have any namem, you are free to choose what you think is 
most appropriate. 

The documentation is here:
http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.odeint.html

In your system function the time is not used because the system is time 
invariant. But in a more advanced model you might use the time too, for 
example the virus particles might survive longer outside the human body in 
winter (`beta` a function of time).

I think a good way to write system functions is like this:

def sir_system(states, time):
'''Defining SIR System of Equations'''
s, i, r = states
ds_dt = -beta * s * i
di_dt = beta * s * i - gamma * i
dr_dt = gamma * i
return np.array([ds_dt, di_dt, dr_dt])


Eike.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 'Installing' Python at runtime? (Civilization)

2011-02-03 Thread Alan Gauld


"C.Y. Ruhulessin"  wrote

When I load up Civilization IV, a Firaxis game, the loading screen 
tells me

"Loading Python".

However, I can't seem to find out where it installs python


It probably doesn't actually install Python it is simply loading
the interpreter into memory.

It probably uses Python as its macro language for configuration
or customisation. To execute those scripts it will need to load
a DLL containing the interpreter code. I don't know for sure
but I'd guess that's what it means.


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Ideas and good examples

2011-02-03 Thread Alan Gauld

"David Goering"  wrote

1) Does anyone have ideas for small - mid ranged projects where I 
could quickly pick up on the pitfalls of Python but that is also 
useful in some way ?


Check the recent archives we had a very similar thread a week
or two back. (And fairly regularly over the years!)

I had a small idea where I could write a program to sync two folders 
mp3 files based on filename and ID3 Tags with a GUI to control it, 
but would love to hear other ideas.


Go for it, its as good as any to start with. The important thing is
not getting the right project but just getting started on one.

2) Is there some tutorial out there that really leads you from 
scratch to a full blown program (with GUI or Database connection or 
whatever) with Code documentation etc. just to see how one could 
approach it


Thats the intent of the Case Study at the end of my tutorial. It tries
to pull together the threads of the tutor into a single, not too big, 
project

It also includes a couple of false starts that worked then had to be
taken out again. And the code evolves from a simple program to
an OOP version to a GUI version. Its not partricularly pretty code
but its deliberately done the way a typical newbie who had finished
the tutor might go about things.

If your library can get a copy of my book it has a second, much
more methodical and "nicer", case study of a reusable games
framework and 3 games built using it. It has a bit of design behind it
with some diagrams and pseudo-code and a bit of prototyping at
the >>> prompt work before diving into code. It is intended to
show how an intermediate programmer might go about things.
But due to some copyright complexities I can't put that one
on the web site... :-(

HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Ideas and good examples

2011-02-03 Thread Alan Gauld


"Tino Dai"  wrote


Finally you should check out Alan Gauld's page:
http://www.freenetpages.co.uk/hp/alan.gauld/  


That site has been locked for over 2 years. The new 
site has a lot of updates and, of course, a whole new 
rewrite of the tutor for v3! :-)


See the sig...

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] best practice: throw exception or set a flag?

2011-02-03 Thread Alex Hall
Hi all,
I am wondering what the best way to do the following would be: throw
an exception, or always return an object but set an error flag if
something goes wrong? Here is an example:

class c:
 def __init__(self):
  self.error=False
 def func(self, val):
  if val!=10: self.error=True

someObj=c()
someObj.func(5)
if someObj.error: #do stuff

OR:

class c:
 def __init__(self):
  self.error=False
 def func(self, val):
  if val!=10: throw ValueError #I know the syntax is wrong

someObj=c()
try:
 someObj.func(5)
except:
 #do stuff

Which is the "standard" way when dealing with objects? Throw
exceptions or always return an object, even if said object has an
error and may therefore not have data beyond an error code and
message? If I go the exception route, can I somehow put a message into
the exception, maybe adding it as an attribute of my custom exception
class? I assume so...
except e:
 print e.message

or something like that. I know I have research to do about the
specifics of all this, but before I go off and look it all up I am
wondering if it is the best way to go as far as standards and best
coding practices. This is still that api wrapper, so I am not the only
one who may end up using this file and I want to make it into
something that is useable and does what people expect. TIA.


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] print "Hello, World!"

2011-02-03 Thread Steven D'Aprano

Doug Marvel wrote:
[...]

I am hoping for a link to a somewhat comprehensive online resource
that explains from the beginning in English, plain English, as this is
the only language I speak. Something to get my foot in the door would
be awesome.


Another very important resource to use is the Python source code. As 
they say, "Use the Source, Luke!".


The source code for the Python compiler itself is written in C, but 
Python comes with many standard library modules written in pure Python. 
They vary in size, complexity and clarity. Not all of them are "best 
practice", but none of them are truly bad.


Under Linux, you can find the source code (usually) somewhere like this:

/usr/lib/python2.5/
/usr/local/lib/python3.1/

You can find out where the source code lives this way:

>>> import calendar
>>> calendar.__file__
'/usr/local/lib/python3.1/calendar.py'

or just use your operating system's Find Files utility to search for the 
file.


Don't be concerned if some modules go completely over your head. They 
haven't been written for beginners. Nevertheless, they are a great way 
to see good quality Python code in action. If nothing else, you can read 
the comments and docstrings.


However, let me give you a warning... unless you are an expert, it is 
*vital* that you treat these files as READ ONLY. If you start changing 
the files, you will confuse yourself greatly when things start 
mysteriously breaking, and everyone else says "It works for me when I 
try it".


(Actually, even as an expert, you should be very wary about changing the 
standard library. If you do, it won't be *standard* any more, will it?)



--
Steven

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] best practice: throw exception or set a flag?

2011-02-03 Thread Emile van Sebille

On 2/3/2011 4:41 PM Alex Hall said...

Hi all,
I am wondering what the best way to do the following would be: throw
an exception, or always return an object but set an error flag if
something goes wrong? Here is an example:

class c:
  def __init__(self):
   self.error=False
  def func(self, val):
   if val!=10: self.error=True

someObj=c()
someObj.func(5)
if someObj.error: #do stuff

OR:

class c:
  def __init__(self):
   self.error=False
  def func(self, val):
   if val!=10: throw ValueError #I know the syntax is wrong

someObj=c()
try:
  someObj.func(5)
except:
  #do stuff

Which is the "standard" way when dealing with objects? Throw
exceptions or always return


Yes, throw exceptions and always return the expected result.  Expecting 
non-class (ie, external to the class) access to verify that the result 
is usable would be , I think, generally frowned upon.



Emile



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] RE module is working ?

2011-02-03 Thread Steven D'Aprano

Karim wrote:


*Indeed what's the matter with RE module!?*

You should really fix the problem with your email program first;
Thunderbird issue with bold type (appears as stars) but I don't know how 
to fix it yet.


A man when to a doctor and said, "Doctor, every time I do this, it 
hurts. What should I do?"


The doctor replied, "Then stop doing that!"

:)

Don't add bold or any other formatting to things which should be program 
code. Even if it looks okay in *your* program, you don't know how it 
will look in other people's programs. If you need to draw attention to 
something in a line of code, add a comment, or talk about it in the 
surrounding text.



[...]
That is not the thing I want. I want to escape any " which are not 
already escaped.
The sed regex  '/\([^\\]\)\?"/\1\\"/g' is exactly what I need (I have 
made regex on unix since 15 years).


Which regex? Perl regexes? sed or awk regexes? Extended regexes? GNU 
posix compliant regexes? grep or egrep regexes? They're all different.


In any case, I am sorry, I don't think your regex does what you say. 
When I try it, it doesn't work for me.


[steve@sylar ~]$ echo 'Some \"text"' | sed -e 's/\([^\\]\)\?"/\1\\"/g'
Some \\"text\"

I wouldn't expect it to work. See below.

By the way, you don't need to escape the brackets or the question mark:

[steve@sylar ~]$ echo 'Some \"text"' | sed -re 's/([^\\])?"/\1\\"/g'
Some \\"text\"



For me the equivalent python regex is buggy: r'([^\\])?"', r'\1\\"'


No it is not.

The pattern you are matching does not do what you think it does. "Zero 
or one of not-backslash, followed by a quote" will match a single quote 
*regardless* of what is before it. This is true even in sed, as you can 
see above, your sed regex matches both quotes.


\" will match, because the regular expression will match zero 
characters, followed by a quote. So the regex is correct.


>>> match = r'[^\\]?"'  # zero or one not-backslash followed by quote
>>> re.search(match, r'aaa\"aaa').group()
'"'

Now watch what happens when you call re.sub:


>>> match = r'([^\\])?"'  # group 1 equals a single non-backslash
>>> replace = r'\1\\"'  # group 1 followed by \ followed by "
>>> re.sub(match, replace, '')  # no matches
''
>>> re.sub(match, replace, 'aa"aa')  # one match
'aa\\"aa'
>>> re.sub(match, replace, '"')  # one match, but there's no group 1
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/lib/python3.1/re.py", line 166, in sub
return _compile(pattern, flags).sub(repl, string, count)
  File "/usr/local/lib/python3.1/re.py", line 303, in filter
return sre_parse.expand_template(template, match)
  File "/usr/local/lib/python3.1/sre_parse.py", line 807, in 
expand_template

raise error("unmatched group")
sre_constants.error: unmatched group

Because group 1 was never matched, Python's re.sub raised an error. It 
is not a very informative error, but it is valid behaviour.


If I try the same thing in sed, I get something different:

[steve@sylar ~]$ echo '"Some text' | sed -re 's/([^\\])?"/\1\\"/g'
\"Some text

It looks like this version of sed defines backreferences on the 
right-hand side to be the empty string, in the case that they don't 
match at all. But this is not standard behaviour. The sed FAQs say that 
this behaviour will depend on the version of sed you are using:


"Seds differ in how they treat invalid backreferences where no 
corresponding group occurs."


http://sed.sourceforge.net/sedfaq3.html

So you can't rely on this feature. If it works for you, great, but it 
may not work for other people.



When you delete the ? from the Python regex, group 1 is always valid, 
and you don't get an exception. Or if you ensure the input always 
matches group 1, no exception:


>>> match = r'([^\\])?"'
>>> replace = r'\1\\"'
>>> re.sub(match, replace, 'a"a"a"a') # group 1 always matches
'a\\"a\\"a\\"a'

(It still won't do what you want, but that's a *different* problem.)



Jamie Zawinski wrote:

  Some people, when confronted with a problem, think "I know,
  I'll use regular expressions." Now they have two problems.

How many hours have you spent trying to solve this problem using 
regexes? This is a *tiny* problem that requires an easy solution, not 
wrestling with a programming language that looks like line-noise.


This should do what you ask for:

def escape(text):
"""Escape any double-quote characters if and only if they
aren't already escaped."""
output = []
escaped = False
for c in text:
if c == '"' and not escaped:
output.append('\\')
elif c == '\\':
output.append('\\')
escaped = True
continue
output.append(c)
escaped = False
return ''.join(output)


Armed with this helper function, which took me two minutes to write, I 
can do this:


>>> text = 'Some text with backslash-quotes \\" and plain quotes " 
together.'

>>> print escape(text)
Some text with backslash-quotes \" an

Re: [Tutor] Ideas and good examples

2011-02-03 Thread David Goering

Hello,
Thanks for the input so far. Alan I saw a Message about your website 
right after I sent away my question and it definetly looks like a good 
place to start... especially the sections from Advanced Topics onwards.
It says v3 is Under Construction, how long do you expect it to be like 
this. Is it worth waiting or should I just go ahead with v2 ?
Sorry if its a repeated question... I will sift through the Archives to 
find other ideas to similar questions.
But anyway thanks so far, if someone still has new ideas or links they 
are always welcome :)

--
David
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Ideas and good examples

2011-02-03 Thread Robert

On 2011-02-03 19:14:40 -0500, Alan Gauld said:


"Tino Dai"  wrote


Finally you should check out Alan Gauld's page:
http://www.freenetpages.co.uk/hp/alan.gauld/


That site has been locked for over 2 years. The new
site has a lot of updates and, of course, a whole new
rewrite of the tutor for v3! :-)

See the sig...


That's awesome. I think I have the original book you did in storage 
(many moons ago).  :-)


--
Robert


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] best practice: throw exception or set a flag?

2011-02-03 Thread Steven D'Aprano

Alex Hall wrote:

Hi all,
I am wondering what the best way to do the following would be: throw
an exception, or always return an object but set an error flag if
something goes wrong? 


Raise an exception. Error flags are an anti-pattern -- a software idiom 
that you should not follow.


The problem with flags is that callers will forget to check them, which 
leads to problems being revealed far away from where the problem was 
caused. That makes it *really* hard to debug.


result = function(x)  # fails and sets an error flag in result
do_something_else()
data = [1, 2, 'a', result, 'xyz']  # store
another_function(data)
# ...
# ...
# lots more code here
# ...
# ...
x = data[3]
do_something_with(x)

which then blows up, because x is invalid but you haven't checked the 
error flag. The problem actually was with the *original* x, all the way 
back at the start, but that's been thrown away now, never to be seen 
again, which makes it hard to debug why it failed.


A million, billion, trillion times worse is if you have a single global 
error flag! That's *disastrous*, because you MUST check the flag 
*immediately*, otherwise it can be cleared.


x = function(1)  # fails
y = another_function(1000)
if global_error_flag:
# seems to be safe to use x
process(x)  # but it isn't, and this blows up

the problem being that another_function makes a second call to 
function(), only this one succeeds and resets the global flag. If you do 
this, the ghost of a thousand programmers will drag your spirit off to 
the nether regions of Hell, where you will have to debug the Windows 
kernel using only the `ed` editor on a keyboard missing the letters "x", 
"s" and "1" for all of eternity.


For those who don't know the `ed` editor, it is "the standard Unix editor":

http://www.gnu.org/fun/jokes/ed.msg.html




Which is the "standard" way when dealing with objects? Throw
exceptions or always return an object, even if said object has an
error and may therefore not have data beyond an error code and
message? If I go the exception route, can I somehow put a message into
the exception, maybe adding it as an attribute of my custom exception
class? I assume so...
except e:
 print e.message


Most standard is to raise an exception. The syntax is:

raise ValueError("any message you like")

or use whatever error type suits your problem. You can even define your 
own exception types:


class MyError(ValueError):
pass


Less common, but still reasonable, is to raise an error sentinel in 
place of the normal result. For example, re.match() and re.search() 
return None when there is nothing found, instead of a MatchObject. 
Another example, str.find() returns -1.


The disadvantage of this is obvious:

>>> string = "Nobody expects the Portuguese Inquisition!"
>>> offset = string.find("Spanish")
>>> print(string[offset:])  # expecting "Spanish Inquisition!"
!


For special purposes, like mathematics, you can define error values that 
propagate through calculations. Python has half-hearted support for 
such "Not A Number" codes:


>>> nan = float('nan')
>>> nan + 1  # doesn't fail, but propagates
nan
>>> nan**2
nan
>>> nan - 1000
nan

as well as infinity. But you should consider this a very specialized 
solution (as well as a lot of work!!!).


Another non-standard solution is to return a pair of values, a flag plus 
the value you actually want:


flag, value = function(1)
if flag:
do_something_with(value)
else:
process_error()




or something like that. I know I have research to do about the
specifics of all this, but before I go off and look it all up I am
wondering if it is the best way to go as far as standards and best
coding practices. This is still that api wrapper, so I am not the only
one who may end up using this file and I want to make it into
something that is useable and does what people expect. TIA.


Then there is absolutely not even a shadow of a doubt: use exceptions.



--
Steven

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 'Installing' Python at runtime? (Civilization)

2011-02-03 Thread Steven D'Aprano

Alan Gauld wrote:


"C.Y. Ruhulessin"  wrote

When I load up Civilization IV, a Firaxis game, the loading screen 
tells me

"Loading Python".

However, I can't seem to find out where it installs python


It probably doesn't actually install Python it is simply loading
the interpreter into memory.


That's what it says... it says "Loading Python", not installing it. It 
would include a version of Python when the game was installed, possibly 
embedded in the Civilization game itself. *Installing* Python each time 
you start the game would be silly.


To find out where it is installed, use your operating system's Find 
Files utility to search for a file named "python". If you don't find it, 
that could mean they have renamed it something else, or it is embedded 
in the game where you can't get to it.




It probably uses Python as its macro language for configuration
or customisation. To execute those scripts it will need to load
a DLL containing the interpreter code. I don't know for sure
but I'd guess that's what it means.


Many games use Python as a scripting language. (Lua is another popular 
choice.) The multiplayer game EVE maintains a special port of Python 
called "stackless".



--
Steven

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] best practice: throw exception or set a flag?

2011-02-03 Thread Alex Hall
Thanks to all for the answers. Sounds like exceptions are most
definitely the way to go, and I will definitely put them in. In fact,
this should make the wrapper a bit cleaner since I am not constantly
checking for errors in variables and returning empty objects. Besides,
I wouldn't want my soul stolen by angry programmers and doomed to
working on Windows, let alone kernel debugging... :) Now, if it were
Android, there might be something to the idea.

On 2/3/11, Steven D'Aprano  wrote:
> Alex Hall wrote:
>> Hi all,
>> I am wondering what the best way to do the following would be: throw
>> an exception, or always return an object but set an error flag if
>> something goes wrong?
>
> Raise an exception. Error flags are an anti-pattern -- a software idiom
> that you should not follow.
>
> The problem with flags is that callers will forget to check them, which
> leads to problems being revealed far away from where the problem was
> caused. That makes it *really* hard to debug.
>
> result = function(x)  # fails and sets an error flag in result
> do_something_else()
> data = [1, 2, 'a', result, 'xyz']  # store
> another_function(data)
> # ...
> # ...
> # lots more code here
> # ...
> # ...
> x = data[3]
> do_something_with(x)
>
> which then blows up, because x is invalid but you haven't checked the
> error flag. The problem actually was with the *original* x, all the way
> back at the start, but that's been thrown away now, never to be seen
> again, which makes it hard to debug why it failed.
>
> A million, billion, trillion times worse is if you have a single global
> error flag! That's *disastrous*, because you MUST check the flag
> *immediately*, otherwise it can be cleared.
>
> x = function(1)  # fails
> y = another_function(1000)
> if global_error_flag:
>  # seems to be safe to use x
>  process(x)  # but it isn't, and this blows up
>
> the problem being that another_function makes a second call to
> function(), only this one succeeds and resets the global flag. If you do
> this, the ghost of a thousand programmers will drag your spirit off to
> the nether regions of Hell, where you will have to debug the Windows
> kernel using only the `ed` editor on a keyboard missing the letters "x",
> "s" and "1" for all of eternity.
>
> For those who don't know the `ed` editor, it is "the standard Unix editor":
>
> http://www.gnu.org/fun/jokes/ed.msg.html
>
>
>
>> Which is the "standard" way when dealing with objects? Throw
>> exceptions or always return an object, even if said object has an
>> error and may therefore not have data beyond an error code and
>> message? If I go the exception route, can I somehow put a message into
>> the exception, maybe adding it as an attribute of my custom exception
>> class? I assume so...
>> except e:
>>  print e.message
>
> Most standard is to raise an exception. The syntax is:
>
> raise ValueError("any message you like")
>
> or use whatever error type suits your problem. You can even define your
> own exception types:
>
> class MyError(ValueError):
>  pass
>
>
> Less common, but still reasonable, is to raise an error sentinel in
> place of the normal result. For example, re.match() and re.search()
> return None when there is nothing found, instead of a MatchObject.
> Another example, str.find() returns -1.
>
> The disadvantage of this is obvious:
>
>  >>> string = "Nobody expects the Portuguese Inquisition!"
>  >>> offset = string.find("Spanish")
>  >>> print(string[offset:])  # expecting "Spanish Inquisition!"
> !
>
>
> For special purposes, like mathematics, you can define error values that
> propagate through calculations. Python has half-hearted support for
> such "Not A Number" codes:
>
>  >>> nan = float('nan')
>  >>> nan + 1  # doesn't fail, but propagates
> nan
>  >>> nan**2
> nan
>  >>> nan - 1000
> nan
>
> as well as infinity. But you should consider this a very specialized
> solution (as well as a lot of work!!!).
>
> Another non-standard solution is to return a pair of values, a flag plus
> the value you actually want:
>
> flag, value = function(1)
> if flag:
>  do_something_with(value)
> else:
>  process_error()
>
>
>
>> or something like that. I know I have research to do about the
>> specifics of all this, but before I go off and look it all up I am
>> wondering if it is the best way to go as far as standards and best
>> coding practices. This is still that api wrapper, so I am not the only
>> one who may end up using this file and I want to make it into
>> something that is useable and does what people expect. TIA.
>
> Then there is absolutely not even a shadow of a doubt: use exceptions.
>
>
>
> --
> Steven
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
_