To make a method or attribute private

2013-01-20 Thread iMath
To make a method or attribute private (inaccessible from the outside), simply 
start its
name with two underscores

《Beginning Python From Novice to Professional》

but there is another saying goes:
Beginning a variable name with a single underscore indicates that the variable 
should be treated as ‘private’.

I test both these 2 rules ,it seems only names that start with two underscores 
are REAL private methods or attributes .

>>> class A:
... def __init__(self):
... self.a = 'a'
... self._a = '_a'
... self.__a = '__a'
...



>>> ap = A()
>>> ap.a
'a'
>>> ap._a
'_a'
>>> ap.__a
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: A instance has no attribute '__a'

so what is your opinion about single leading underscore and private methods or 
attributes?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: To make a method or attribute private

2013-01-20 Thread Chris Angelico
On Sun, Jan 20, 2013 at 8:17 PM, iMath  wrote:
> so what is your opinion about single leading underscore and private methods 
> or attributes?

Didn't this get discussed recently?

http://mail.python.org/pipermail/python-list/2013-January/638687.html

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


Re: Parent module adsite.adsiteviews.mainhanlder does not exist

2013-01-20 Thread Jason Friedman
> I created a django project using django 1.4.2. There is one 'app'(adsite) in 
> this project. And It works. But when I copied some 'py' files into the 'app' 
> folder, I got "Parent module adsite.adsiteviews.mainhanlder does not exist." 
> Should I register the new files to __init__ in the 'app'? Did new coped files 
> break the "import" rules?

I do not know if this is your problem, and I know little about django,
but is "mainhanlder" a typographical error?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: To make a method or attribute private

2013-01-20 Thread iMath
在 2013年1月17日星期四UTC+8上午9时04分00秒,alex23写道:
> On Jan 17, 10:34 am, "iMath" <2281570...@qq.com> wrote:
> 
> > To make a method or attribute private (inaccessible from the outside), 
> > simply start its
> 
> > name with two underscores
> 
> >
> 
> > but there is another saying goes:
> 
> > Beginning a variable name with a single underscore indicates that the 
> > variable should be treated as ‘private’.
> 
> > I test both these 2 rules ,it seems only names that start with two 
> > underscores are REAL private methods or attributes .
> 
> > so what is your opinion about single leading underscore and private methods 
> > or attributes?
> 
> 
> 
> The key word in the second quote is "indicates". Placing a single
> 
> underscore before an attribute name does nothing but _show_ other
> 
> programmers that you consider this to be part of the implementation
> 
> rather than the interface, and that you make no guarantees of its
> 
> continued existence over time.
> 
> 
> 
> More importantly, however: there is no real concept of "private"
> 
> attributes in Python. Try this at the command prompt:
> 
> 
> 
> >>> ap._A__a
> 
> '__a'
> 
> 
> 
> It's still readable, and it's still writable too. The double-
> 
> underscore naming is referred to as "name mangling" and while it's
> 
> often passed off as the way to make private methods in Python (the
> 
> tutorial even states this), what it is really intended for is to
> 
> ensure that multiple inheritance works correctly:
> 
> 
> 
> >>> class A(object):
> 
> ...   foo = 'A'
> 
> ...   def get_A_foo(self):
> 
> ... return self.foo
> 
> ...
> 
> >>> class B(object):
> 
> ...   foo = 'B'
> 
> ...   def get_B_foo(self):
> 
> ... return self.foo
> 
> ...
> 
> >>> class C(A, B):
> 
> ...   def __init__(self):
> 
> ... super(C, self).__init__()
> 
> ...
> 
> >>> c = C()
> 
> >>> c.get_A_foo()
> 
> 'A'
> 
> >>> c.get_B_foo()
> 
> 'A'
> 
> 
> 
> Here, we haven't mangled the attribute 'foo' on either A or B, so on
> 
> the instance of C, which inherits from both, the inherited methods are
> 
> referring to the same attribute, which is A's in this case due to the
> 
> method resolution order. By re-naming 'foo' on both A and B to
> 
> '__foo', each can then refer to their _own_ attribute, and also allow
> 
> for C to have its own 'foo' attribute which doesn't conflict with
> 
> either of them:
> 
> 
> 
> >>> class A(object):
> 
> ...   __foo = 'A'
> 
> ...   def get_A_foo(self):
> 
> ... return self.__foo
> 
> ...
> 
> >>> class B(object):
> 
> ...   __foo = 'B'
> 
> ...   def get_B_foo(self):
> 
> ... return self.__foo
> 
> ...
> 
> >>> class C(A, B):
> 
> ...   foo = 'C'
> 
> ...   def __init__(self):
> 
> ... super(C, self).__init__()
> 
> ...
> 
> >>> c = C()
> 
> >>> c.get_A_foo()
> 
> 'A'
> 
> >>> c.get_B_foo()
> 
> 'B'
> 
> >>> c.foo
> 
> 'C'
> 
> 
> 
> There is no way to make an externally private attribute. This is
> 
> generally considered a good thing by most Python developers: if I
> 
> _need_ to access your class's implementation, I can do so, but the
> 
> name mangling forces me to be aware that this is something you don't
> 
> recommend doing. You'll often hear the term "consenting adults" used
> 
> to refer to this, meaning we can all decide for ourselves if we're
> 
> willing to risk using an implementation detail.

what's the meaning of 'object' in 
class A(object)
and 
class B(object) ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: To make a method or attribute private

2013-01-20 Thread Steven D'Aprano
On Sun, 20 Jan 2013 06:52:32 -0800, iMath wrote:

[snip many dozens of lines of irrelevant text]

> what's the meaning of 'object' in
> class A(object)
> and
> class B(object) ?


Please trim your replies. We don't need to scroll past page after page of 
irrelevant text which we have already read.

"object" is the name of the base class defining common methods used by 
all new classes. In Python 2, you should always subclass object, unless 
you are subclassing something else. In Python 3, subclassing object is 
automatic, whether you write it or not.

In Python 2, if you fail to subclass object, you get an "old-style 
class", and features like property, classmethod, staticmethod, super and 
multiple inheritance may not work at all, or be buggy.



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


Re: PyWart: Exception error paths far too verbose

2013-01-20 Thread Terry Reedy

On 1/20/2013 1:08 AM, Steven D'Aprano wrote:

On Sat, 19 Jan 2013 19:15:55 -0800, Ramchandra Apte wrote:

[snip dozens of irrelevant quoted lines]

Right-click the file in the traceback and there is an "Go to file/line"
option.



Please trim your replies so that the reader doesn't have to scroll
through page after page of irrelevant text they've already read.

Thank you.


Quite aside from the fact that there already was a quick reply telling 
me the same thing. A properly threaded reader would have placed it just 
below my post.


--
Terry Jan Reedy

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


Re: ANN: Python training "text movies"

2013-01-20 Thread Franck Ditter
In article ,
 Mitya Sirenef  wrote:

> On 01/19/2013 04:32 AM, Franck Ditter wrote:
> > In article ,
> >   Mitya Sirenef  wrote:
> >
> >> On 01/14/2013 01:34 AM, Franck Ditter wrote:
> >>> In article ,
> >>>Jason Friedman  wrote:
> >>>
> > That is right; I would also add that it may be overwhelming for a newbie
> > to be reading through a large "wall of text" -- here you have blank
> > space after the current paragraph so the attention is focused even more
> > on the last few lines.
> >
> > Additionally, since instructions scroll automatically, I can space them
> > out more than you would conventionally do in a manual.
> >
>  Pretty cool.
> >>> When reading the source of the Web page which shows the scroll,
> >>> I can't find the reference to the text displayed. Only "text"...
> >>> How may we use the software which generates the Javascript ?
> >>> Thanks, it's cool.
> >>>
> >>>   franck
> >> Thanks!
> >>
> >>the text is in var commands = ...
> >>
> >> You can download the generator script here:
> >>
> >> https://github.com/pythonbyexample/PBE/blob/master/code/jstmovie.py
> >>
> >> (you also need to grab  tmovies dir)
> > When looking at the source of the page :
> > http://lightbird.net/larks/tmovies/strings.html
> > I find commands = []
> > I can't guess where the strings displayed come from...
> >
> >  franck
> 
> Look 10 lines below that line.
> 
> 
> I have also added a related page that allows you to paste your own
> text to make a movie; it's linked from the same page with the
> list of generated t-movies.
> 
> (that page does not let you use typewriter effect or custom pauses
> though).
> 
>   - mitya

I'm probably blind but 10 line after the line "commands = []", I find :

var commands = [
[
"text",
" "
],
[
"text",
" "
],
]

but nothing concrete ! How come ?

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


Re: ANN: Python training "text movies"

2013-01-20 Thread Franck Ditter
In article ,
 Franck Ditter  wrote:

> In article ,
>  Mitya Sirenef  wrote:
> 
> > On 01/19/2013 04:32 AM, Franck Ditter wrote:
> > > In article ,
> > >   Mitya Sirenef  wrote:
> > >
> > >> On 01/14/2013 01:34 AM, Franck Ditter wrote:
> > >>> In article ,
> > >>>Jason Friedman  wrote:
> > >>>
> > > That is right; I would also add that it may be overwhelming for a 
> > > newbie
> > > to be reading through a large "wall of text" -- here you have blank
> > > space after the current paragraph so the attention is focused even 
> > > more
> > > on the last few lines.
> > >
> > > Additionally, since instructions scroll automatically, I can space 
> > > them
> > > out more than you would conventionally do in a manual.
> > >
> >  Pretty cool.
> > >>> When reading the source of the Web page which shows the scroll,
> > >>> I can't find the reference to the text displayed. Only "text"...
> > >>> How may we use the software which generates the Javascript ?
> > >>> Thanks, it's cool.
> > >>>
> > >>>   franck
> > >> Thanks!
> > >>
> > >>the text is in var commands = ...
> > >>
> > >> You can download the generator script here:
> > >>
> > >> https://github.com/pythonbyexample/PBE/blob/master/code/jstmovie.py
> > >>
> > >> (you also need to grab  tmovies dir)
> > > When looking at the source of the page :
> > > http://lightbird.net/larks/tmovies/strings.html
> > > I find commands = []
> > > I can't guess where the strings displayed come from...
> > >
> > >  franck
> > 
> > Look 10 lines below that line.
> > 
> > 
> > I have also added a related page that allows you to paste your own
> > text to make a movie; it's linked from the same page with the
> > list of generated t-movies.
> > 
> > (that page does not let you use typewriter effect or custom pauses
> > though).
> > 
> >   - mitya
> 
> I'm probably blind but 10 line after the line "commands = []", I find :
> 
> var commands = [
> [
> "text",
> " "
> ],
> [
> "text",
> " "
> ],
> ]
> 
> but nothing concrete ! How come ?
> 
> franck

OK OK found ! Thanks.

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


Re: ANN: Python training "text movies"

2013-01-20 Thread Franck Ditter
In article ,
 Franck Ditter  wrote:

> In article ,
>  Franck Ditter  wrote:
> 
> > In article ,
> >  Mitya Sirenef  wrote:
> > 
> > > On 01/19/2013 04:32 AM, Franck Ditter wrote:
> > > > In article ,
> > > >   Mitya Sirenef  wrote:
> > > >
> > > >> On 01/14/2013 01:34 AM, Franck Ditter wrote:
> > > >>> In article ,
> > > >>>Jason Friedman  wrote:
> > > >>>
> > > > That is right; I would also add that it may be overwhelming for a 
> > > > newbie
> > > > to be reading through a large "wall of text" -- here you have blank
> > > > space after the current paragraph so the attention is focused even 
> > > > more
> > > > on the last few lines.
> > > >
> > > > Additionally, since instructions scroll automatically, I can space 
> > > > them
> > > > out more than you would conventionally do in a manual.
> > > >
> > >  Pretty cool.
> > > >>> When reading the source of the Web page which shows the scroll,
> > > >>> I can't find the reference to the text displayed. Only "text"...
> > > >>> How may we use the software which generates the Javascript ?
> > > >>> Thanks, it's cool.
> > > >>>
> > > >>>   franck
> > > >> Thanks!
> > > >>
> > > >>the text is in var commands = ...
> > > >>
> > > >> You can download the generator script here:
> > > >>
> > > >> https://github.com/pythonbyexample/PBE/blob/master/code/jstmovie.py
> > > >>
> > > >> (you also need to grab  tmovies dir)
> > > > When looking at the source of the page :
> > > > http://lightbird.net/larks/tmovies/strings.html
> > > > I find commands = []
> > > > I can't guess where the strings displayed come from...
> > > >
> > > >  franck
> > > 
> > > Look 10 lines below that line.
> > > 
> > > 
> > > I have also added a related page that allows you to paste your own
> > > text to make a movie; it's linked from the same page with the
> > > list of generated t-movies.
> > > 
> > > (that page does not let you use typewriter effect or custom pauses
> > > though).
> > > 
> > >   - mitya
> > 
> > I'm probably blind but 10 line after the line "commands = []", I find :
> > 
> > var commands = [
> > [
> > "text",
> > " "
> > ],
> > [
> > "text",
> > " "
> > ],
> > ]
> > 
> > but nothing concrete ! How come ?
> > 
> > franck
> 
> OK OK found ! Thanks.
> 
>franck

When executing jstmovie.py, it complains :
'template.html' not found in tmovies...

franck

tmovies/template.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Python training "text movies"

2013-01-20 Thread Mitya Sirenef

On 01/20/2013 12:54 PM, Franck Ditter wrote:

In article  ,

> Franck Ditter  wrote:
>
>> In article ,
>> Franck Ditter  wrote:
>>
>>> In article ,
>>> Mitya Sirenef  wrote:
>>>
 On 01/19/2013 04:32 AM, Franck Ditter wrote:
> In article ,
> Mitya Sirenef  wrote:
>
>> On 01/14/2013 01:34 AM, Franck Ditter wrote:
>>> In article ,
>>> Jason Friedman  wrote:
>>>
> That is right; I would also add that it may be overwhelming 
for a newbie
> to be reading through a large "wall of text" -- here you have 
blank
> space after the current paragraph so the attention is focused 
even more

> on the last few lines.
>
> Additionally, since instructions scroll automatically, I can 
space them

> out more than you would conventionally do in a manual.
>
 Pretty cool.
>>> When reading the source of the Web page which shows the scroll,
>>> I can't find the reference to the text displayed. Only "text"...
>>> How may we use the software which generates the Javascript ?
>>> Thanks, it's cool.
>>>
>>> franck
>> Thanks!
>>
>> the text is in var commands = ...
>>
>> You can download the generator script here:
>>
>> https://github.com/pythonbyexample/PBE/blob/master/code/jstmovie.py
>>
>> (you also need to grab tmovies dir)
> When looking at the source of the page :
> http://lightbird.net/larks/tmovies/strings.html
> I find commands = []
> I can't guess where the strings displayed come from...
>
> franck

 Look 10 lines below that line.


 I have also added a related page that allows you to paste your own
 text to make a movie; it's linked from the same page with the
 list of generated t-movies.

 (that page does not let you use typewriter effect or custom pauses
 though).

 - mitya
>>>
>>> I'm probably blind but 10 line after the line "commands = []", I find :
>>>
>>> var commands = [
>>> [
>>> "text",
>>> " "
>>> ],
>>> [
>>> "text",
>>> " "
>>> ],
>>> ]
>>>
>>> but nothing concrete ! How come ?
>>>
>>> franck
>>
>> OK OK found ! Thanks.
>>
>> franck
>
> When executing jstmovie.py, it complains :
> 'template.html' not found in tmovies...
>
> franck
>
> tmovies/template.html

As I've said upthread, you need to download tmovies dir from
the same repository where jstmovie.py is located:

https://github.com/pythonbyexample/PBE/tree/master/code/


 - mitya



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Admiration for a quality or an art can be so strong that it deters us from
striving to possess it.  Friedrich Nietzsche

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


Re: Messing with the GC

2013-01-20 Thread Jens Thoms Toerring

Hi,

thank you for the explanations. I had overlooked the
cyclic nature of what I had produced here and, of course,
the GC can't be blamed for not collecting objects that are
part of a cycle. The other question about the last refe-
rence to an object vanishing within a method call (which,
as I now clearly understand, can't happen and wouldn't make
much sense) was triggered by a segmentation fault I get
when I do something similar in PySide, so I was getting
worried if it might be due to a GC issue. Now I know its
got to be something different;-)

 Thanks and best regards, Jens
-- 
  \   Jens Thoms Toerring  ___  j...@toerring.de
   \__  http://toerring.de
-- 
http://mail.python.org/mailman/listinfo/python-list


RE Help splitting CVS data

2013-01-20 Thread Garry
I'm trying to manipulate family tree data using Python.
I'm using linux and Python 2.7.3 and have data files saved as Linux formatted 
cvs files
The data appears in this format:

Marriage,Husband,Wife,Date,Place,Source,Note0x0a
Note: the Source field or the Note field can contain quoted data (same as the 
Place field)

Actual data:
[F0244],[I0690],[I0354],1916-06-08,"Neely's Landing, Cape Gir. Co, MO",,0x0a
[F0245],[I0692],[I0355],1919-09-04,"Cape Girardeau Co, MO",,0x0a

code snippet follows:

import os
import re
#I'm using the following regex in an attempt to decode the data:
RegExp2 = 
"^(\[[A-Z]\d{1,}\])\,(\[[A-Z]\d{1,}\])\,(\[[A-Z]\d{1,}\])\,(\d{,4}\-\d{,2}\-\d{,2})\,(.*|\".*\")\,(.*|\".*\")\,(.*|\".*\")"
#
line = "[F0244],[I0690],[I0354],1916-06-08,\"Neely's Landing, Cape Gir. Co, 
MO\",,"
#
(Marriage,Husband,Wife,Date,Place,Source,Note) = re.split(RegExp2,line)
#
#However, this does not decode the 7 fields.
# The following error is displayed:
Traceback (most recent call last):
  File "", line 1, in 
ValueError: too many values to unpack
#
# When I use xx the fields apparently get unpacked.
xx = re.split(RegExp2,line)
#
>>> print xx[0]

>>> print xx[1]
[F0244]
>>> print xx[5]
"Neely's Landing, Cape Gir. Co, MO"
>>> print xx[6]

>>> print xx[7]

>>> print xx[8]

Why is there an extra NULL field before and after my record contents?
I'm stuck, comments and solutions greatly appreciated.

Garry 

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


Re: RE Help splitting CVS data

2013-01-20 Thread Mitya Sirenef

On 01/20/2013 05:04 PM, Garry wrote:

I'm trying to manipulate family tree data using Python.
I'm using linux and Python 2.7.3 and have data files saved as Linux formatted 
cvs files
The data appears in this format:

Marriage,Husband,Wife,Date,Place,Source,Note0x0a
Note: the Source field or the Note field can contain quoted data (same as the 
Place field)

Actual data:
[F0244],[I0690],[I0354],1916-06-08,"Neely's Landing, Cape Gir. Co, MO",,0x0a
[F0245],[I0692],[I0355],1919-09-04,"Cape Girardeau Co, MO",,0x0a

code snippet follows:

import os
import re
#I'm using the following regex in an attempt to decode the data:
RegExp2 = 
"^(\[[A-Z]\d{1,}\])\,(\[[A-Z]\d{1,}\])\,(\[[A-Z]\d{1,}\])\,(\d{,4}\-\d{,2}\-\d{,2})\,(.*|\".*\")\,(.*|\".*\")\,(.*|\".*\")"
#
line = "[F0244],[I0690],[I0354],1916-06-08,\"Neely's Landing, Cape Gir. Co, 
MO\",,"
#
(Marriage,Husband,Wife,Date,Place,Source,Note) = re.split(RegExp2,line)
#
#However, this does not decode the 7 fields.
# The following error is displayed:
Traceback (most recent call last):
   File "", line 1, in 
ValueError: too many values to unpack
#
# When I use xx the fields apparently get unpacked.
xx = re.split(RegExp2,line)
#

print xx[0]
print xx[1]

[F0244]

print xx[5]

"Neely's Landing, Cape Gir. Co, MO"

print xx[6]
print xx[7]
print xx[8]

Why is there an extra NULL field before and after my record contents?
I'm stuck, comments and solutions greatly appreciated.

Garry




Gosh, you really don't want to use regex to split csv lines like that

Use csv module:

>>> s
'[F0244],[I0690],[I0354],1916-06-08,"Neely\'s Landing, Cape Gir. Co, 
MO",,0x0a'

>>> import csv
>>> r = csv.reader([s])
>>> for l in r: print(l)
...
['[F0244]', '[I0690]', '[I0354]', '1916-06-08', "Neely's Landing, Cape 
Gir. Co, MO", '', '0x0a']



the arg to csv.reader can be the file object (or a list of lines).

 - mitya


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: Messing with the GC

2013-01-20 Thread Terry Reedy

On 1/20/2013 3:09 PM, Jens Thoms Toerring wrote:


 thank you for the explanations. I had overlooked the
cyclic nature of what I had produced here and, of course,
the GC can't be blamed for not collecting objects that are
part of a cycle. The other question about the last refe-
rence to an object vanishing within a method call (which,
as I now clearly understand, can't happen and wouldn't make
much sense) was triggered by a segmentation fault I get
when I do something similar in PySide, so I was getting
worried if it might be due to a GC issue. Now I know its
got to be something different;-)


Perhaps the hardest part of writing C extensions to CPython directly in 
C (versus something like Cython) is properly balancing increfs and 
decrefs. An incref without a later decref can lead to a memory leak. A 
decref without a preceding incref (so CPython thinks the object can be 
deleted, when it should not be) can lead to segfaults. So I would report 
PySide code leading to segfaults to the PySide people.


--
Terry Jan Reedy

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


Re: RE Help splitting CVS data

2013-01-20 Thread Terry Reedy

On 1/20/2013 5:04 PM, Garry wrote:

I'm trying to manipulate family tree data using Python.
I'm using linux and Python 2.7.3 and have data files saved as Linux formatted 
cvs files

...

I'm stuck, comments and solutions greatly appreciated.


Why are you not using the cvs module?

--
Terry Jan Reedy

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


Re: Help splitting CVS data

2013-01-20 Thread Dave Angel

On 01/20/2013 05:04 PM, Garry wrote:

I'm trying to manipulate family tree data using Python.
I'm using linux and Python 2.7.3 and have data files saved as Linux formatted 
cvs files
The data appears in this format:

Marriage,Husband,Wife,Date,Place,Source,Note0x0a
Note: the Source field or the Note field can contain quoted data (same as the 
Place field)

Actual data:
[F0244],[I0690],[I0354],1916-06-08,"Neely's Landing, Cape Gir. Co, MO",,0x0a
[F0245],[I0692],[I0355],1919-09-04,"Cape Girardeau Co, MO",,0x0a

code snippet follows:

import os
import re
#I'm using the following regex in an attempt to decode the data:
RegExp2 = 
"^(\[[A-Z]\d{1,}\])\,(\[[A-Z]\d{1,}\])\,(\[[A-Z]\d{1,}\])\,(\d{,4}\-\d{,2}\-\d{,2})\,(.*|\".*\")\,(.*|\".*\")\,(.*|\".*\")"
#


Well, you lost me about there.  For a csv file, why not use the csv module:


import csv

ifile  = open('test.csv', "rb")
reader = csv.reader(ifile)


For reference, see http://docs.python.org/2/library/csv.html

and for sample use and discussion, see

http://www.linuxjournal.com/content/handling-csv-files-python

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


Re: To make a method or attribute private

2013-01-20 Thread alex23
On Jan 20, 7:23 pm, Chris Angelico  wrote:
> On Sun, Jan 20, 2013 at 8:17 PM, iMath  wrote:
> > so what is your opinion about single leading underscore and private methods 
> > or attributes?
>
> Didn't this get discussed recently?
>
> http://mail.python.org/pipermail/python-list/2013-January/638687.html
>
> ChrisA

Isn't that a link to the same post that started this thread? :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: To make a method or attribute private

2013-01-20 Thread Dave Angel

On 01/20/2013 06:14 PM, alex23 wrote:

On Jan 20, 7:23 pm, Chris Angelico  wrote:

On Sun, Jan 20, 2013 at 8:17 PM, iMath  wrote:

so what is your opinion about single leading underscore and private methods or 
attributes?


Didn't this get discussed recently?

http://mail.python.org/pipermail/python-list/2013-January/638687.html

ChrisA


Isn't that a link to the same post that started this thread? :)



No, that's the one that started the earlier thread, by the same name, 
three whole days ago.  iMath posted an apparently complete duplicate of 
his earlier message.



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


Re: RE Help splitting CVS data

2013-01-20 Thread Tim Chase

On 01/20/13 16:16, Terry Reedy wrote:

On 1/20/2013 5:04 PM, Garry wrote:

I'm trying to manipulate family tree data using Python.
I'm using linux and Python 2.7.3 and have data files saved as Linux formatted 
cvs files

...

I'm stuck, comments and solutions greatly appreciated.


Why are you not using the cvs module?


that's an easy answer:

>>> import cvs
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named cvs


Now the *csv* module... ;-)

-tkc




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


Re: ANN: Python training "text movies"

2013-01-20 Thread Steven D'Aprano
On Sun, 20 Jan 2013 18:54:03 +0100, Franck Ditter wrote:

[snip quoting NINE levels deep]

> When executing jstmovie.py, it complains : 'template.html' not found in
> tmovies...

Please trim unnecessary quoted text out of your replies. We don't need to 
read page after page of irrelevant comments that we've already read 
before.

Thank you.

If there is more quoted text than new text you have written, or quoting 
exceeds 3, maybe 4 levels deep, then there probably is too much 
unnecessary quoting.


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


Re: RE Help splitting CVS data

2013-01-20 Thread Garry
On Sunday, January 20, 2013 3:04:39 PM UTC-7, Garry wrote:
> I'm trying to manipulate family tree data using Python.
> 
> I'm using linux and Python 2.7.3 and have data files saved as Linux formatted 
> cvs files
> 
> The data appears in this format:
> 
> 
> 
> Marriage,Husband,Wife,Date,Place,Source,Note0x0a
> 
> Note: the Source field or the Note field can contain quoted data (same as the 
> Place field)
> 
> 
> 
> Actual data:
> 
> [F0244],[I0690],[I0354],1916-06-08,"Neely's Landing, Cape Gir. Co, MO",,0x0a
> 
> [F0245],[I0692],[I0355],1919-09-04,"Cape Girardeau Co, MO",,0x0a
> 
> 
> 
> code snippet follows:
> 
> 
> 
> import os
> 
> import re
> 
> #I'm using the following regex in an attempt to decode the data:
> 
> RegExp2 = 
> "^(\[[A-Z]\d{1,}\])\,(\[[A-Z]\d{1,}\])\,(\[[A-Z]\d{1,}\])\,(\d{,4}\-\d{,2}\-\d{,2})\,(.*|\".*\")\,(.*|\".*\")\,(.*|\".*\")"
> 
> #
> 
> line = "[F0244],[I0690],[I0354],1916-06-08,\"Neely's Landing, Cape Gir. Co, 
> MO\",,"
> 
> #
> 
> (Marriage,Husband,Wife,Date,Place,Source,Note) = re.split(RegExp2,line)
> 
> #
> 
> #However, this does not decode the 7 fields.
> 
> # The following error is displayed:
> 
> Traceback (most recent call last):
> 
>   File "", line 1, in 
> 
> ValueError: too many values to unpack
> 
> #
> 
> # When I use xx the fields apparently get unpacked.
> 
> xx = re.split(RegExp2,line)
> 
> #
> 
> >>> print xx[0]
> 
> 
> 
> >>> print xx[1]
> 
> [F0244]
> 
> >>> print xx[5]
> 
> "Neely's Landing, Cape Gir. Co, MO"
> 
> >>> print xx[6]
> 
> 
> 
> >>> print xx[7]
> 
> 
> 
> >>> print xx[8]
> 
> 
> 
> Why is there an extra NULL field before and after my record contents?
> 
> I'm stuck, comments and solutions greatly appreciated.
> 
> 
> 
> Garry

Thanks everyone for your comments.  I'm new to Python, but can get around in 
Perl and regular expressions.  I sure was taking the long way trying to get the 
cvs data parsed.  

Sure hope to teach myself python.  Maybe I need to look into courses offered at 
the local Jr College!

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


Re: How do functions get access to builtins?

2013-01-20 Thread Rouslan Korneychuk

On 01/19/2013 09:59 PM, Steven D'Aprano wrote:

I've been playing around with ChainedMap in Python 3.3, and run into
something which perplexes me. Let's start with an ordinary function that
accesses one global and one builtin.


x = 42
def f():
 print(x)


If you call f(), it works as expected. But let's make a version with no
access to builtins, and watch it break:

from types import FunctionType
g = FunctionType(f.__code__, {'x': 23})


If you call g(), you get an exception:

py> g()
Traceback (most recent call last):
   File "", line 1, in 
   File "", line 2, in f
NameError: global name 'print' is not defined


(Don't be fooled by the traceback referring to "f" rather than g.
That's because g's code was copied from f.)

We can add support for builtins:

import builtins  # use __builtin__ with no "s" in Python 2
g.__globals__['__builtins__'] = builtins  # Note the "s" in the key.


and now calling g() prints 23, as expected.

Now let me try the same thing using Python 3.3's ChainMap. Unfortunately,
functions insist that their __global__ is a dict, so we fool it into
accepting a ChainMap with some multiple inheritance trickery:


from collections import ChainMap
class ChainedDict(ChainMap, dict):
 pass

d = ChainedDict({}, {'x': 23}, {'x': 42})
assert d['x'] == 23
g = FunctionType(f.__code__, d)


As before, calling g() raises NameError, "global name 'print' is not
defined". So I expected to be able to fix it just as I did before:

g.__globals__['__builtins__'] = builtins


But it doesn't work -- I still get the same NameError. Why does this not
work here, when it works for a regular dict?



I found the answer in Python's source code. When you execute a code 
object, PyFrame_New is called which gets 'bultins' from 'globals', but 
inside PyFrame_New (defined on line 596 of Objects/frameobject.c) is the 
following (line 613):


  builtins = PyDict_GetItem(globals, builtin_object);

Unlike PyObject_GetItem, PyDict_GetItem is specialized for dict objects. 
Your ChainedDict class uses ChainMaps's storage and leaves dict's 
storage empty, so PyDict_GetItem doesn't find anything.




I can fix it by adding the builtins into the ChainMap:

g.__globals__.maps.append(builtins.__dict__)


And now calling g() prints 23 as expected.



The reason this works is unlike PyFrame_New, the LOAD_GLOBAL opcode 
first checks if globals' type is dict (and not a subclass), and falls 
back to using PyObject_GetItem if it's anything else.



Interestingly: it looks like it could be fixed easily enough. Unless 
there are other places where globals is assumed to be a dict object, it 
would just be a matter of doing the same check and fallback in 
PyFrame_New that is done in LOAD_GLOBAL (technically, you could just use 
PyObject_GetItem; obviously, this is an optimization).



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


Re: Messing with the GC

2013-01-20 Thread Jens Thoms Toerring
Terry Reedy  wrote:
> On 1/20/2013 3:09 PM, Jens Thoms Toerring wrote:

> >  thank you for the explanations. I had overlooked the
> > cyclic nature of what I had produced here and, of course,
> > the GC can't be blamed for not collecting objects that are
> > part of a cycle. The other question about the last refe-
> > rence to an object vanishing within a method call (which,
> > as I now clearly understand, can't happen and wouldn't make
> > much sense) was triggered by a segmentation fault I get
> > when I do something similar in PySide, so I was getting
> > worried if it might be due to a GC issue. Now I know its
> > got to be something different;-)

> Perhaps the hardest part of writing C extensions to CPython directly in
> C (versus something like Cython) is properly balancing increfs and
> decrefs. An incref without a later decref can lead to a memory leak. A
> decref without a preceding incref (so CPython thinks the object can be
> deleted, when it should not be) can lead to segfaults.

Definitely - I got started with Python having to write glue
code to get Python to work with a C++ library. And keeping
track of which side thinks it owns an object can sometimes
be a bit of a challenge...

> So I would report PySide code leading to segfaults to the
> PySide people.

Now that I'm more sure that it's unlikely to be a Python GC
related issue (or my not understanding what I'm doing, to be
precise) this is on my to-do list. But first I have to distill
things down to a very short example program still exhibiting
the problem - and experience tells me that this will most li-
kely result in the realization that it's not a PySide issue
at all but some misunderstanding on my side;-)

 Best regards, Jens
-- 
  \   Jens Thoms Toerring  ___  j...@toerring.de
   \__  http://toerring.de
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: To make a method or attribute private

2013-01-20 Thread iMath
在 2013年1月17日星期四UTC+8上午8时34分22秒,iMath写道:
> To make a method or attribute private (inaccessible from the outside), simply 
> start its 
> name with two underscores
> 
> 
> 《Beginning Python From Novice to Professional》
> 
> 
> but there is another saying goes:
> Beginning a variable name with a single underscore indicates that the 
> variable should be treated as ‘private’.
> 
> 
> I test both these 2 rules ,it seems only names that start with two 
> underscores are REAL private methods or attributes .
> 
> 
> >>> class A:
> ...     def __init__(self):
> ...         self.a = 'a'
> ...         self._a = '_a'
> ...         self.__a = '__a'
> ...
> 
> 
> 
> 
> 
> 
> >>> ap = A()
> >>> ap.a
> 'a'
> >>> ap._a
> '_a'
> >>> ap.__a
> Traceback (most recent call last):
>   File "", line 1, in ?
> AttributeError: A instance has no attribute '__a'
> 
> 
> so what is your opinion about single leading underscore and private methods 
> or attributes?

so there is no REAL private variable in Python but conversion exists in it that 
python programmer should follow and recognize .right ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: To make a method or attribute private

2013-01-20 Thread Chris Angelico
On Mon, Jan 21, 2013 at 12:14 PM, iMath  wrote:
> so there is no REAL private variable in Python but conversion exists in it 
> that python programmer should follow and recognize .right ?

That's about it. If you think about C++ public members as the
"interface" and private/protected members as the "implementation",
then Python's convention is a leading underscore on the latter; you
can reasonably expect that non-underscore members can be trusted to be
maintained, but underscored members will quite possibly change in
subsequent versions.

Among smart people, conventions like this are all you need.

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


Re: RE Help splitting CVS data

2013-01-20 Thread Chris Angelico
On Mon, Jan 21, 2013 at 11:41 AM, Garry  wrote:
> Thanks everyone for your comments.  I'm new to Python, but can get around in 
> Perl and regular expressions.  I sure was taking the long way trying to get 
> the cvs data parsed.

As has been hinted by Tim, you're actually talking about csv data -
Comma Separated Values. Not to be confused with cvs, an old vcs. (See?
The v can go anywhere...) Not a big deal, but it's much easier to find
stuff on PyPI or similar when you have the right keyword to search
for!

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


Re: To make a method or attribute private

2013-01-20 Thread alex23
On Jan 21, 9:32 am, Dave Angel  wrote:
> On 01/20/2013 06:14 PM, alex23 wrote:
>
> > On Jan 20, 7:23 pm, Chris Angelico  wrote:
> >> On Sun, Jan 20, 2013 at 8:17 PM, iMath  wrote:
> >>> so what is your opinion about single leading underscore and private 
> >>> methods or attributes?
>
> >> Didn't this get discussed recently?
>
> >>http://mail.python.org/pipermail/python-list/2013-January/638687.html
>
> >> ChrisA
>
> > Isn't that a link to the same post that started this thread? :)
>
> No, that's the one that started the earlier thread, by the same name,
> three whole days ago.  iMath posted an apparently complete duplicate of
> his earlier message.

The link is to a post of the same date as the original of this thread,
and the very first response is mine, same as with this thread. I'm
still not seeing the dupe?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: To make a method or attribute private

2013-01-20 Thread Mitya Sirenef

On 01/20/2013 09:24 PM, alex23 wrote:

On Jan 21, 9:32 am, Dave Angel   wrote:

>> On 01/20/2013 06:14 PM, alex23 wrote:
>>
>>> On Jan 20, 7:23 pm, Chris Angelico  wrote:
 On Sun, Jan 20, 2013 at 8:17 PM, iMath  wrote:
> so what is your opinion about single leading underscore and 
private methods or attributes?

>>
 Didn't this get discussed recently?
>>
 http://mail.python.org/pipermail/python-list/2013-January/638687.html
>>
 ChrisA
>>
>>> Isn't that a link to the same post that started this thread? :)
>>
>> No, that's the one that started the earlier thread, by the same name,
>> three whole days ago. iMath posted an apparently complete duplicate of
>> his earlier message.
>
> The link is to a post of the same date as the original of this thread,
> and the very first response is mine, same as with this thread. I'm
> still not seeing the dupe?

I do see the duplicate in my reader..  -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

To knock a thing down, especially if it is cocked at an arrogant angle, is
a deep delight of the blood.
George Santayana


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


Re: To make a method or attribute private

2013-01-20 Thread Steven D'Aprano
On Sun, 20 Jan 2013 17:14:36 -0800, iMath wrote:

[...]
> so there is no REAL private variable in Python but conversion exists in
> it that python programmer should follow and recognize .right ?

There are no "REAL private variables" in most languages. Consider the C++ 
trick "#define private public". Or pointer tricks, or using reflection in 
Java.

Yes, the convention in Python is that names starting with a single 
underscore should be considered private implementation details.



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


Else statement executing when it shouldnt

2013-01-20 Thread eli m
an else statement is running when it shouldnt be. It is on the last line. 
Whenever i am in the math or game function, when i type in main, it goes back 
to the start of the program, but it also says not a valid function. I am 
stumped!
Here is my code:
#Cmd 
#Created By Eli M.
#import modules
import random
import math
gtn = 0
print ("Type in help for a list of cmd functions")
#initiate main loop
cmd = 0
while cmd == 0:
#ask for input on function
function = raw_input("Type in a function:")
#start math loop
if function == "math":
run = 0
while run == 0:
#ask for math operation
type = raw_input("What math operation do you want to use?")
if type == "multiplication":
x = raw_input("Type in your first number:")
y = raw_input("Multiply your first number by:")
try:
ans = int(x) * int(y)
print (ans)
try:
ans = float(x) * float(y)
print (ans)
except ValueError, err:
print ("Not a valid number")
except OverflowError, err:
print ("Number too large")
#division math function
if type == "division":
x = raw_input("Type in your first number:")
y = raw_input("Divide your first number by:")
try:
ans = float(x) / float(y)
print (ans)
except ZeroDivisionError, err:
print ("Can't divide by zero")
except ValueError, err:
print ("Not a valid number")
except OverflowError, err:
print ("Number too large")
#subtraction math function
if type == "subtraction":
x = raw_input("Type in your first number:")
y = raw_input("Subtract your first number by:")
try:
ans = float(x) - float(y)
print (ans)
except ValueError, err:
print ("Not a valid number")
#addition math function
if type == "addition":
x = raw_input("Type in your first number:")
y = raw_input("Add your first number by:")
try:
ans = float(x) + float(y)
print (ans)
except ValueError, err:
try:
ans = int(x) + int(y)
print (ans)
except ValueError, err:
print ("Not a valid number")
except OverflowError, err:
print ("Number too large")
#square root math function
if type == "square root":
x = raw_input("Type in your number:")
try:
y = float(x)
z = math.sqrt(y)
print (z)
except ValueError, err:
print ("Not a valid number")
except OverflowError, err:
print ("Number too large")

#to the power of... math function
if type == "power":
x = raw_input("Type in your number:")
y = raw_input("Multiply your first number by the power of:")
try:
ans = float(x) ** float(y)
print (ans)
except OverflowError, err:
print ("Number too large")
except ValueError, err:
print ("Not a valid number")
#break the math loop
if type == "main":
run = 1
#absolute value math function
if type == "absolute value":
try:
x = float(raw_input("Type in your number:"))
y = math.fabs(x)
print (y)
except ValueError, err:
print ("Not a valid number")
if function == "random number":
try:
x = int(raw_input("Minimum number:"))
y = int(raw_input("Maximum number:"))
num = random.randint(x, y)
print (num)
except ValueError, err:
print ("Not a valid number")
if function == "games":
games = 0
while games == 0:
gamechoice = raw_input("What game do you want to play:")
if gamechoice == "guess the number":
run = 0
while run == 0:
print ("I am thinking of a number between 1 and 20")
num = random.randint(1, 20)
num = int(num)
guesses = 0
guessestaken = 0

Re: To make a method or attribute private

2013-01-20 Thread Chris Angelico
On Mon, Jan 21, 2013 at 2:27 PM, Steven D'Aprano
 wrote:
> On Sun, 20 Jan 2013 17:14:36 -0800, iMath wrote:
>
> [...]
>> so there is no REAL private variable in Python but conversion exists in
>> it that python programmer should follow and recognize .right ?
>
> There are no "REAL private variables" in most languages. Consider the C++
> trick "#define private public". Or pointer tricks, or using reflection in
> Java.

Uhh, that's like saying there are no REAL floats in C, because you can
#define float int
And pointer tricks, well, you can do anything with raw memory access.
These aren't proofs that something doesn't exist, they're proofs that
trying to enforce privacy is bound to fail - so you may as well strip
that code from your compiler/interpreter and go with the Python style.
Much easier.

I agree with your point, just not your argument. :)

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


Re: Else statement executing when it shouldnt

2013-01-20 Thread Roy Smith
In article <2cc6791f-ba56-406c-a5b0-b23023caf...@googlegroups.com>,
 eli m  wrote:

> an else statement is running when it shouldnt be. It is on the last line. 
> Whenever i am in the math or game function, when i type in main, it goes back 
> to the start of the program, but it also says not a valid function. I am 
> stumped!
> Here is my code:

[many lines of code elided]

TL;DNR :-)

A basic debugging technique is to try to find the minimum amount of code 
that can reproduce the problem.

Find some hunk of lines that you're pretty sure can't be at fault, and 
delete them.  See if you can still reproduce the problem.  Assuming you 
can, delete another hunk of code.  Keep going until you're down to the 
smallest possible amount of code which demonstrates the problem.

There's a couple of good things that come out of this.  One is that it's 
likely that in the course of doing this, you'll figure out what's wrong.  
The other is that if you can't figure it out, at least now you'll have 
something that's easy to show somebody else when you ask for help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Else statement executing when it shouldnt

2013-01-20 Thread Chris Angelico
On Mon, Jan 21, 2013 at 3:40 PM, eli m  wrote:
> an else statement is running when it shouldnt be. It is on the last line. 
> Whenever i am in the math or game function, when i type in main, it goes back 
> to the start of the program, but it also says not a valid function. I am 
> stumped!

Check your indentation levels. I see a few things here that look odd:

> if function == "help":
> while helpfunc == 0:
> if helpmain == "main":
> else:

What is the else meant to bind to? The innermost if? The 'if function
== "help"'? It's currently binding to the while.

Recommendation: Break this up! Your main loop is huge! It's way too
easy to get lost in it. And while you're at it, consider unifying some
of the similar blocks of code. The solution to both issues is simple:
Use functions. Have you been taught about them yet?

Also, side tip: Be honest about homework. I'm fairly sure that's what
this is. :)

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


Re: Else statement executing when it shouldnt

2013-01-20 Thread eli m
On Sunday, January 20, 2013 8:54:13 PM UTC-8, René Klačan wrote:
> You have to break while loop not to execute else branch
> 
> 
> Rene
> 
> 
> 
Can you explain in more detail please.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Else statement executing when it shouldnt

2013-01-20 Thread René Klačan
You have to break while loop not to execute else branch

Rene

On Mon, Jan 21, 2013 at 5:40 AM, eli m  wrote:

> an else statement is running when it shouldnt be. It is on the last line.
> Whenever i am in the math or game function, when i type in main, it goes
> back to the start of the program, but it also says not a valid function. I
> am stumped!
> Here is my code:
> #Cmd
> #Created By Eli M.
> #import modules
> import random
> import math
> gtn = 0
> print ("Type in help for a list of cmd functions")
> #initiate main loop
> cmd = 0
> while cmd == 0:
> #ask for input on function
> function = raw_input("Type in a function:")
> #start math loop
> if function == "math":
> run = 0
> while run == 0:
> #ask for math operation
> type = raw_input("What math operation do you want to use?")
> if type == "multiplication":
> x = raw_input("Type in your first number:")
> y = raw_input("Multiply your first number by:")
> try:
> ans = int(x) * int(y)
> print (ans)
> try:
> ans = float(x) * float(y)
> print (ans)
> except ValueError, err:
> print ("Not a valid number")
> except OverflowError, err:
> print ("Number too large")
> #division math function
> if type == "division":
> x = raw_input("Type in your first number:")
> y = raw_input("Divide your first number by:")
> try:
> ans = float(x) / float(y)
> print (ans)
> except ZeroDivisionError, err:
> print ("Can't divide by zero")
> except ValueError, err:
> print ("Not a valid number")
> except OverflowError, err:
> print ("Number too large")
> #subtraction math function
> if type == "subtraction":
> x = raw_input("Type in your first number:")
> y = raw_input("Subtract your first number by:")
> try:
> ans = float(x) - float(y)
> print (ans)
> except ValueError, err:
> print ("Not a valid number")
> #addition math function
> if type == "addition":
> x = raw_input("Type in your first number:")
> y = raw_input("Add your first number by:")
> try:
> ans = float(x) + float(y)
> print (ans)
> except ValueError, err:
> try:
> ans = int(x) + int(y)
> print (ans)
> except ValueError, err:
> print ("Not a valid number")
> except OverflowError, err:
> print ("Number too large")
> #square root math function
> if type == "square root":
> x = raw_input("Type in your number:")
> try:
> y = float(x)
> z = math.sqrt(y)
> print (z)
> except ValueError, err:
> print ("Not a valid number")
> except OverflowError, err:
> print ("Number too large")
>
> #to the power of... math function
> if type == "power":
> x = raw_input("Type in your number:")
> y = raw_input("Multiply your first number by the power
> of:")
> try:
> ans = float(x) ** float(y)
> print (ans)
> except OverflowError, err:
> print ("Number too large")
> except ValueError, err:
> print ("Not a valid number")
> #break the math loop
> if type == "main":
> run = 1
> #absolute value math function
> if type == "absolute value":
> try:
> x = float(raw_input("Type in your number:"))
> y = math.fabs(x)
> print (y)
> except ValueError, err:
> print ("Not a valid number")
> if function == "random number":
> try:
> x = int(raw_input("Minimum number:"))
> y = int(raw_input("Maximum number:"))
> num = random.randint(x, y)
> print (num)
> except ValueError, err:
> print ("Not a valid number")
> if function == "games":
> games = 0
> while games == 0:
> gamechoice = raw_input("What game do you want to play:")
> if

Re: Else statement executing when it shouldnt

2013-01-20 Thread eli m

> 
> 
> 
> Your else is lined up with while, not with if.
> 
> 
> 
>   -m
> 
> 
> 
> 
> 
> -- 
> 
> Lark's Tongue Guide to Python: http://lightbird.net/larks/
> 
> 
> 
> When a friend succeeds, I die a little.  Gore Vidal
Its lined up. It got messed up when i copied the code into the post.

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


Re: Else statement executing when it shouldnt

2013-01-20 Thread eli m
On Sunday, January 20, 2013 8:40:47 PM UTC-8, eli m wrote:
hint: Use the comments in the code to find out where my error is.
> 
> Here is my code:
> 
> #Cmd 
> 
> #Created By Eli M.
> 
> #import modules
> 
> import random
> 
> import math
> 
> gtn = 0
> 
> print ("Type in help for a list of cmd functions")
> 
> #initiate main loop
> 
> cmd = 0
> 
> while cmd == 0:
> 
> #ask for input on function
> 
> function = raw_input("Type in a function:")
> 
> #start math loop
> 
> if function == "math":
> 
> run = 0
> 
> while run == 0:
> 
> #ask for math operation
> 
> type = raw_input("What math operation do you want to use?")
> 
> if type == "multiplication":
> 
> x = raw_input("Type in your first number:")
> 
> y = raw_input("Multiply your first number by:")
> 
> try:
> 
> ans = int(x) * int(y)
> 
> print (ans)
> 
> try:
> 
> ans = float(x) * float(y)
> 
> print (ans)
> 
> except ValueError, err:
> 
> print ("Not a valid number")
> 
> except OverflowError, err:
> 
> print ("Number too large")
> 
> #division math function
> 
> if type == "division":
> 
> x = raw_input("Type in your first number:")
> 
> y = raw_input("Divide your first number by:")
> 
> try:
> 
> ans = float(x) / float(y)
> 
> print (ans)
> 
> except ZeroDivisionError, err:
> 
> print ("Can't divide by zero")
> 
> except ValueError, err:
> 
> print ("Not a valid number")
> 
> except OverflowError, err:
> 
> print ("Number too large")
> 
> #subtraction math function
> 
> if type == "subtraction":
> 
> x = raw_input("Type in your first number:")
> 
> y = raw_input("Subtract your first number by:")
> 
> try:
> 
> ans = float(x) - float(y)
> 
> print (ans)
> 
> except ValueError, err:
> 
> print ("Not a valid number")
> 
> #addition math function
> 
> if type == "addition":
> 
> x = raw_input("Type in your first number:")
> 
> y = raw_input("Add your first number by:")
> 
> try:
> 
> ans = float(x) + float(y)
> 
> print (ans)
> 
> except ValueError, err:
> 
> try:
> 
> ans = int(x) + int(y)
> 
> print (ans)
> 
> except ValueError, err:
> 
> print ("Not a valid number")
> 
> except OverflowError, err:
> 
> print ("Number too large")
> 
> #square root math function
> 
> if type == "square root":
> 
> x = raw_input("Type in your number:")
> 
> try:
> 
> y = float(x)
> 
> z = math.sqrt(y)
> 
> print (z)
> 
> except ValueError, err:
> 
> print ("Not a valid number")
> 
> except OverflowError, err:
> 
> print ("Number too large")
> 
> 
> 
> #to the power of... math function
> 
> if type == "power":
> 
> x = raw_input("Type in your number:")
> 
> y = raw_input("Multiply your first number by the power 
> of:")
> 
> try:
> 
> ans = float(x) ** float(y)
> 
> print (ans)
> 
> except OverflowError, err:
> 
> print ("Number too large")
> 
> except ValueError, err:
> 
> print ("Not a valid number")
> 
> #break the math loop
> 
> if type == "main":
> 
> run = 1
> 
> #absolute value math function
> 
> if type == "absolute value":
> 
> try:
> 
> x = float(raw_input("Type in your number:"))
> 
> y = math.fabs(x)
> 
> print (y)
> 
> except ValueError, err:
> 
> print ("Not a valid number")
> 
> if function == "random number":
> 
> try:
> 
> x = int(raw_input("Minimum number:"))
> 
> y = int(raw_input("Maximum number:"))
> 
> num = random.randint(x, y)
> 
> print (num)
> 
> except ValueError, err:
> 
> print ("Not a valid number")
> 
> if function == "games":
> 
>

Re: Else statement executing when it shouldnt

2013-01-20 Thread eli m
On Sunday, January 20, 2013 8:52:12 PM UTC-8, Chris Angelico wrote:
> On Mon, Jan 21, 2013 at 3:40 PM, eli m  wrote:
> 
> > an else statement is running when it shouldnt be. It is on the last line. 
> > Whenever i am in the math or game function, when i type in main, it goes 
> > back to the start of the program, but it also says not a valid function. I 
> > am stumped!
> 
> 
> 
> Check your indentation levels. I see a few things here that look odd:
> 
> 
> 
> > if function == "help":
> 
> > while helpfunc == 0:
> 
> > if helpmain == "main":
> 
> > else:
> 
> 
> 
> What is the else meant to bind to? The innermost if? The 'if function
> 
> == "help"'? It's currently binding to the while.
> 
> 
> 
> Recommendation: Break this up! Your main loop is huge! It's way too
> 
> easy to get lost in it. And while you're at it, consider unifying some
> 
> of the similar blocks of code. The solution to both issues is simple:
> 
> Use functions. Have you been taught about them yet?
> 
> 
> 
> Also, side tip: Be honest about homework. I'm fairly sure that's what
> 
> this is. :)
> 
> 
> 
> ChrisA

Its not homework. It is a personal project.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Else statement executing when it shouldnt

2013-01-20 Thread Mitya Sirenef

On 01/20/2013 11:40 PM, eli m wrote:
an else statement is running  when it shouldnt be. It is on the last line. Whenever i am in the math 
or game function, when i type in main, it goes back to the start of the 
program, but it also says not a valid function. I am stumped!

> Here is my code:
> #Cmd
> #Created By Eli M.
> #import modules
> import random
> import math
> gtn = 0
> print ("Type in help for a list of cmd functions")
> #initiate main loop
> cmd = 0
> while cmd == 0:
> #ask for input on function
> function = raw_input("Type in a function:")
> #start math loop
> if function == "math":
> run = 0
> while run == 0:
> #ask for math operation
> type = raw_input("What math operation do you want to use?")
> if type == "multiplication":
> x = raw_input("Type in your first number:")
> y = raw_input("Multiply your first number by:")
> try:
> ans = int(x) * int(y)
> print (ans)
> try:
> ans = float(x) * float(y)
> print (ans)
> except ValueError, err:
> print ("Not a valid number")
> except OverflowError, err:
> print ("Number too large")
> #division math function
> if type == "division":
> x = raw_input("Type in your first number:")
> y = raw_input("Divide your first number by:")
> try:
> ans = float(x) / float(y)
> print (ans)
> except ZeroDivisionError, err:
> print ("Can't divide by zero")
> except ValueError, err:
> print ("Not a valid number")
> except OverflowError, err:
> print ("Number too large")
> #subtraction math function
> if type == "subtraction":
> x = raw_input("Type in your first number:")
> y = raw_input("Subtract your first number by:")
> try:
> ans = float(x) - float(y)
> print (ans)
> except ValueError, err:
> print ("Not a valid number")
> #addition math function
> if type == "addition":
> x = raw_input("Type in your first number:")
> y = raw_input("Add your first number by:")
> try:
> ans = float(x) + float(y)
> print (ans)
> except ValueError, err:
> try:
> ans = int(x) + int(y)
> print (ans)
> except ValueError, err:
> print ("Not a valid number")
> except OverflowError, err:
> print ("Number too large")
> #square root math function
> if type == "square root":
> x = raw_input("Type in your number:")
> try:
> y = float(x)
> z = math.sqrt(y)
> print (z)
> except ValueError, err:
> print ("Not a valid number")
> except OverflowError, err:
> print ("Number too large")
>
> #to the power of... math function
> if type == "power":
> x = raw_input("Type in your number:")
> y = raw_input("Multiply your first number by the power of:")
> try:
> ans = float(x) ** float(y)
> print (ans)
> except OverflowError, err:
> print ("Number too large")
> except ValueError, err:
> print ("Not a valid number")
> #break the math loop
> if type == "main":
> run = 1
> #absolute value math function
> if type == "absolute value":
> try:
> x = float(raw_input("Type in your number:"))
> y = math.fabs(x)
> print (y)
> except ValueError, err:
> print ("Not a valid number")
> if function == "random number":
> try:
> x = int(raw_input("Minimum number:"))
> y = int(raw_input("Maximum number:"))
> num = random.randint(x, y)
> print (num)
> except ValueError, err:
> print ("Not a valid number")
> if function == "games":
> games = 0
> while games == 0:
> gamechoice = raw_input("What game do you want to play:")
> if gamechoice == "guess the number":
> run = 0
> while run == 0:
> print ("I am thinking of a number between 1 and 20")
> num = random.randint(1, 20)
> num = int(num)
> guesses = 0
> guessestaken = 0
> while guesses == 0:
> try:
> guess = raw_input("Your guess:")
> guess = int(guess)
> guessestaken = (guessestaken) + 1
> guessestaken = int(guessestaken)
> if guess == (num):
> print 'Correct! It took you', int(guessestaken), 'guesses!'
> playagain = raw_input("Do you want to play again?")
> if playagain == "yes":
> guesses = 1
> if playagain == "no":
> run = 1
> guesses = 1
> if guess > num:
> print ("My number is lower")
> if guess < num:
> print ("My number is higher")
> except TypeError, err:
> print ("Not a valid number")
> if gamechoice == "main":
> games = 1
>
> #help function
> if function == "help":
> helpfunc = 0
> while helpfunc == 0:
> #show functions
> print ("Functions:")
> print ("Math: multiplication, division, subtraction, addition, square 
root, power, absolute value")

> print ("Random Number")
> print ("Games: Guess the number")
> helpmain = raw_input("Type in main to go back")
> if helpmain == "main":
> #end helpfunction loop
> helpfunc = 1
> cmd = 0
> else:
> print ("Not a valid function")


Your else is lined up with while, not with if.

 -m


--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

When a friend succeeds, I die a little.  Gore Vidal

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


Re: Else statement executing when it shouldnt

2013-01-20 Thread René Klačan
Examples:

# else branch will be executed
i = 0
while i < 5:
i += 1
else:
print('loop is over')


# else branch will be executed
i = 0
while i < 5:
i += 1
if i == 7:
print('i == 7')
break
else:
print('loop is over')


# else branch wont be executed
i = 0
while i < 5:
i += 1
if i == 3:
print('i == 3')
break
else:
print('loop is over')

On Mon, Jan 21, 2013 at 5:57 AM, eli m  wrote:

> On Sunday, January 20, 2013 8:54:13 PM UTC-8, René Klačan wrote:
> > You have to break while loop not to execute else branch
> >
> >
> > Rene
> >
> >
> >
> Can you explain in more detail please.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Else statement executing when it shouldnt

2013-01-20 Thread René Klačan
Examples:

# else branch will be executed
i = 0
while i < 5:
i += 1
else:
print('loop is over')


# else branch will be executed
i = 0
while i < 5:
i += 1
if i == 7:
print('i == 7')
break
else:
print('loop is over')


# else branch wont be executed
i = 0
while i < 5:
i += 1
if i == 3:
print('i == 3')
break
else:
print('loop is over')

On Mon, Jan 21, 2013 at 5:57 AM, eli m  wrote:

> On Sunday, January 20, 2013 8:54:13 PM UTC-8, René Klačan wrote:
> > You have to break while loop not to execute else branch
> >
> >
> > Rene
> >
> >
> >
> Can you explain in more detail please.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: To make a method or attribute private

2013-01-20 Thread alex23
On Jan 21, 2:46 pm, Chris Angelico  wrote:
> These aren't proofs that something doesn't exist, they're proofs that
> trying to enforce privacy is bound to fail

But if you can't enforce it, can you really say it exists?

Semantics, they are fun! I feel another PyWart post coming on...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Else statement executing when it shouldnt

2013-01-20 Thread alex23
On Jan 21, 2:59 pm, eli m  wrote:
> Its lined up. It got messed up when i copied the code into the post.

Sorry, we're not going to take your word for it. Reduce it to the
minimal amount of code that reproduces your error and post that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Else statement executing when it shouldnt

2013-01-20 Thread alex23
On Jan 21, 2:40 pm, eli m  wrote:
> an else statement is running when it shouldnt be. It is
> on the last line. Whenever i am in the math or game
> function, when i type in main, it goes back to the start
> of the program, but it also says not a valid function.
> I am stumped!

Here is your code with the irrelevancy stripped away:

function = raw_input("Type in a function:")
#start math loop
if function == "math":
#math code
if function == "random number":
#random code
if function == "games":
#games code
if function == "help":
#help code
else:
print ("Not a valid function")

Say you enter 'math'. It passes the first condition, so runs the math
code.
It then fails on the next 3 conditions, the last of which has an else,
so if you type _anything_ other than 'help', you'll see "Not a valid
function".

Easy answer, use `elif` ("else if") instead of else for the subsequent
tests:

if function == "math":
#math code
elif function == "random number":
#random code
elif function == "games":
#games code
elif function == "help":
#help code
else:
print ("Not a valid function")

Better answer: read up on real functions, and look into dictionary
dispatch:

def f_math():
   #math code

def f_random_number():
   #random code



function_dispatcher = {
'math': f_math,
'random number': f_random_number,

}

   while cmd == 0:
   function_name = raw_input("Type in a function:")
   if function_name in function_dispatcher:
   function_dispatcher[function_name]()
   else:
   print("Not a valid function")

To have your functions break out of the loop, use a `global` variable
or pass a context object into each function to allow them to set
`cmd`.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Else statement executing when it shouldnt

2013-01-20 Thread alex23
On Jan 21, 2:54 pm, eli m  wrote:
> hint: Use the comments in the code to find out where my error is.

Pro-tip: when people you're asking for help tell you how you can make
it easier for them to help you, a snide response isn't the correct
approach.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Else statement executing when it shouldnt

2013-01-20 Thread Mitya Sirenef

On 01/20/2013 11:59 PM, eli m wrote:



>>
>>
>>
>> Your else is lined up with while, not with if.
>>
>>
>>
>> -m
>>
>>
>>
>>
>>
>> --
>>
>> Lark's Tongue Guide to Python: http://lightbird.net/larks/
>>
>>
>>
>> When a friend succeeds, I die a little. Gore Vidal
> Its lined up. It got messed up when i copied the code into the post.
>

I would recommend using while True: and break vs. while var: as you
have. In most cases while True: works better, especially in case of long
and/or nested 'while' loops, as you have.

'while True' blocks have two advantages: 1. you can break the loop at
any location and 2. when looking at the code, you can tell on which
condition it breaks by looking at the break line.

Even more importantly, break it up into a few functions. The code as you
have it is too hard to work with and to debug.

It's hard to tell what your 'else' is lined up to, or whether some other
lines are mis-aligned, as well.

Generally, try to avoid making a loop if it's 20+ lines; if there are
nested loops, it makes things even worse. Compare:

if something:
while True:
 if not process(): break

def process():
 [... 20 lines that loop ...]
 [ return None to break the loop ]

Now this is really clear, because just by looking at the first three
lines, I know what the loop is supposed to do (process something), that
it continues looping until it returns a false value; when looking at
the function body I don't need to care which block it aligns to, I
already know the entire function body is in the while loop.

HTH, -m



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

The irrational in the human has something about it altogether repulsive and
terrible, as we see in the maniac, the miser, the drunkard or the ape.
George Santayana

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


Re: Forcing Python to detect DocumentRoot

2013-01-20 Thread Ferrous Cranus
Τη Σάββατο, 19 Ιανουαρίου 2013 10:01:15 μ.μ. UTC+2, ο χρήστης Piet van Oostrum 
έγραψε:
> Ferrous Cranus  writes:
> 
> 
> 
> > This is addon domain's counter.py snippet tried to load an image mail.png 
> > and failed because it cant see past its document root
> 
> >
> 
> > 
> 
> > # render html template and print it
> 
> > data = f.read()
> 
> > counter = '''
> 
> >  mailto:supp...@superhost.gr";>  > src="/data/images/mail.png"> 
> 
> >  
> 
> >  
> 
> >   Αριθμός Επισκεπτών 
> 
> >   %d ''' % hits[0]
> 
> > 
> 
> >
> 
> 
> 
> > While from within the same counter.py file
> 
> >
> 
> > # open html template file
> 
> > f = open( '/home/nikos/public_html/test.txt' )
> 
> >
> 
> > opens OK the page file which is also past addons domain's document root
> 
> >
> 
> > Can you help counter.py to load the image? Why does it fail to load it? 
> > Python can have access to ANY filesystempath , no matter from what folder 
> > counter.py script runs from. Correct?
> 
> 
> 
> That piece of code is not opening the image file. It just issues the URL
> 
> for the image file. The file will then be loaded by the browser in a new
> 
> request. The image should be at
> 
> /home/nikos/public_html/data/images/mail.png

Yes the image is this and is located at that folder.

/home/nikos/public_html/cgi-bin/counter.py

that has embedded this line:

mailto:supp...@superhost.gr";>  

can open the file normally as seen if you visit http://superhost.gr


> P.S. I don't understand what you mean by "addon domain".


While

/home/nikos/public_html/cafebar-idea.gr/cgi-bin/counter.py

that has also embedded this line:

mailto:supp...@superhost.gr";>  

cannnot open the file normally.

And the questions iw WHY since python script can open ANY filesystempath
file the user has access too.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Uniquely identifying each & every html template

2013-01-20 Thread Ferrous Cranus
Τη Σάββατο, 19 Ιανουαρίου 2013 11:32:41 μ.μ. UTC+2, ο χρήστης Dennis Lee Bieber 
έγραψε:
> On Sat, 19 Jan 2013 00:39:44 -0800 (PST), Ferrous Cranus
> 
>  declaimed the following in
> 
> gmane.comp.python.general:
> 
> > We need to find a way so even IF:
> 
> > 
> 
> > (filepath gets modified && file content's gets modified) simultaneously the 
> > counter will STILL retains it's value.
> 
> 
> 
>   The only viable solution the /I/ can visualize is one in which any
> 
> operation ON the template file MUST ALSO operate on the counter... That
> 
> is; you only operate on the templates using a front-end application that
> 
> automatically links the counter information every time...
> 
> -- 
> 
>   Wulfraed Dennis Lee Bieber AF6VN
> 
> wlfr...@ix.netcom.comHTTP://wlfraed.home.netcom.com/

CANNOT BE DONE because every html templates has been written by different 
methods.

dramweaver
joomla
notepad++
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Uniquely identifying each & every html template

2013-01-20 Thread Ferrous Cranus
Τη Σάββατο, 19 Ιανουαρίου 2013 11:00:15 π.μ. UTC+2, ο χρήστης Dave Angel έγραψε:
> On 01/19/2013 03:39 AM, Ferrous Cranus wrote:
> 
> > Τη Σάββατο, 19 Ιανουαρίου 2013 12:09:28 π.μ. UTC+2, ο χρήστης Dave Angel 
> > έγραψε:
> 
> >
> 
> >> I don't understand the problem.  A trivial Python script could scan
> 
> >>
> 
> >> through all the files in the directory, checking which ones are missing
> 
> >>
> 
> >> the identifier, and rewriting the file with the identifier added.
> 
> >
> 
> >>
> 
> >> So, since you didn't come to that conclusion, there must be some other
> 
> >>
> 
> >> reason you don't want to edit the files.  Is it that the real sources
> 
> >>
> 
> >> are elsewhere (e.g. Dreamweaver), and whenever one recompiles those
> 
> >>
> 
> >> sources, these files get replaced (without identifiers)?
> 
> >
> 
> > Exactly. Files get modified/updates thus the embedded identifier will be 
> > missing each time. So, relying on embedding code to html template content 
> > is not practical.
> 
> >
> 
> >
> 
> >> If that's the case, then I figure you have about 3 choices:
> 
> >> 1) use the file path as your key, instead of requiring a number
> 
> >
> 
> > No, i cannot, because it would mess things at a later time on when i for 
> > example:
> 
> >
> 
> > 1. mv name.html othername.html   (document's filename altered)
> 
> > 2. mv name.html /subfolder/name.html   (document's filepath altered)
> 
> >
> 
> > Hence, new database counters will be created for each of the above actions, 
> > therefore i will be having 2 counters for the same file, and the latter one 
> > will start from a zero value.
> 
> >
> 
> > Pros: If the file's contents gets updated, that won't affect the counter.
> 
> > Cons: If filepath is altered, then duplicity will happen.
> 
> >
> 
> >
> 
> >> 2) use a hash of the page  (eg. md5) as your key.  of course this could
> 
> >> mean that you get a new value whenever the page is updated.  That's good
> 
> >> in many situations, but you don't give enough information to know if
> 
> >> that's desirable for you or not.
> 
> >
> 
> > That sounds nice! A hash is a mathematical algorithm that produce a unique 
> > number after analyzing each file's contents? But then again what if the 
> > html templated gets updated? That update action will create a new hash for 
> > the file, hence another counter will be created for the same file, same end 
> > result as (1) solution.
> 
> >
> 
> > Pros: If filepath is altered, that won't affect the counter.
> 
> > Cons: If file's contents gets updated the, then duplicity will happen.
> 
> >
> 
> >
> 
> >> 3) Keep an external list of filenames, and their associated id numbers.
> 
> >> The database would be a good place to store such a list, in a separate 
> >> table.
> 
> >
> 
> > I did not understand that solution.
> 
> >
> 
> >
> 
> > We need to find a way so even IF:
> 
> >
> 
> > (filepath gets modified && file content's gets modified) simultaneously the 
> > counter will STILL retains it's value.
> 
> >
> 
> 
> 
> You don't yet have a programming problem, you have a specification 
> 
> problem.  Somehow, you want a file to be considered "the same" even when 
> 
> it's moved, renamed and/or modified.  So all files are the same, and you 
> 
> only need one id.
> 
> Don't pick a mechanism until you have an self-consistent spec.


I do have the specification.

An .html page must retain its database counter value even if its:

(renamed && moved && contents altered)


[original attributes of the file]:

filename: index.html
filepath: /home/nikos/public_html/
contents:  Hello 

[get modified to]:

filename: index2.html
filepath: /home/nikos/public_html/folder/subfolder/
contents:  Hello, people 


The file is still the same, even though its attributes got modified.
We want counter.py script to still be able to "identify" the .html page, hence 
its counter value in order to get increased properly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Uniquely identifying each & every html template

2013-01-20 Thread Chris Angelico
On Mon, Jan 21, 2013 at 6:08 PM, Ferrous Cranus  wrote:
> An .html page must retain its database counter value even if its:
>
> (renamed && moved && contents altered)

Then you either need to tag them in some external way, or have some
kind of tracking operation - for instance, if you require that all
renames/moves be done through a script, that script can update its
pointer. Otherwise, you need magic, and lots of it.

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


Re: ANN: Python training "text movies"

2013-01-20 Thread rusi
On Jan 13, 12:08 pm, Mitya Sirenef  wrote:
> Sure: they play back a list of instructions on use of string methods and
> list comprehensions along with demonstration in a mock-up of the
> interpreter with a different display effect for commands typed into (and
> printed out by) the interpeter. The speed can be changed and the
> playback can be paused.

Hi Mitya.
What do you use for making these 'text-movies'?
[Asking after some googling]
-- 
http://mail.python.org/mailman/listinfo/python-list