Re: [Tutor] __init__() - is it required?

2011-01-10 Thread Alan Gauld


"bob gailer"  wrote


No, init() is only for initialising the object instance.
If you have no local instance spwecific initialisation
you can leave it to the inherited init() aor have no init()
at all.


Well I'd like to expand that a bit. There are cases where I create a 
class attribute and update it each time an instance is created. O


Good point.
init() can legitimately do things other than initialising instance
variables, but conceptually those things are all part of initialising
an instance. Updating class variables is a good example of
such "other things".

Alan G. 



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


Re: [Tutor] Try except really better than if?

2011-01-10 Thread Karim


Thank you Steven, Modulok and Alan for your precious and detailed 
explanations!


I understood that I must not overuse try-except statement and usually 
when the exception could happen exceptionally.
By the way I have this piece of code using elementTree standard module 
and according to Alan this is bad code I guess:


*try: devdb.setDescription(dev.attrib['description'])
except KeyError: pass
try: devdb.setSymbolName(dev.attrib['symbolName'])
except KeyError: pass
try: 
devdb.setSymbolPinOrderMappingList(dev.attrib['symbolPinOrderMappingList'])

except KeyError: pass
try: devdb.setLayoutName(dev.attrib['layoutName'])
except KeyError: pass
try: devdb.setLayoutType(dev.attrib['layoutType'])
except KeyError: pass
*
In fact elementTree *attrib* dictionary attributes could not have 
optionally xml attribute (depending on my xml input file).
Indeed to test existence I try to execute *dev.attrib['//'*]. But I 
can't use only one except
because the other settings could not be processed if one given optional 
xml attribute is not present (except will be raised).

I must did it for each possible attribute.

Do you have an alternative or my way is ok?
I know there is no special case which is enough special to break the 
rule ;o)


Regards
Karim

On 01/10/2011 03:10 AM, Alan Gauld wrote:
ctions are slower than static functions, but that 


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


Re: [Tutor] Checkbox problem in Tkinter

2011-01-10 Thread Alan Gauld


"ANKUR AGGARWAL"  wrote


from Tkinter import *
root=Tk()
var=StringVar()
c=Checkbutton(root,text="hello",variable=var,onvalue="",offvalue="")
c.pack()
root.mainloop()


FWIW I get a different problem, namely that the var does not seem
to get updated nor does changling the var seem to alter the buuttons
state. But at least the button displays OK with 'hello' in the label 
and
I can select/deselect it with the mouse. its just the change to the 
variable that is broken.

If I write an explicit event handler:

def f():
 var = '' if var == '' else ''

Then var changes OK. Here is my code(from Pythonwin):

def f(): global var; var = 'on' if var == 'off' else 'off';print 
var

...

top = Tk()
var = StringVar()
c = Checkbutton(top,text='txt', variable=var, onvalue='on', 
offvalue='off', command=f)

c.pack()
top.mainloop()

off
on
off
on
off
on

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] Try except really better than if?

2011-01-10 Thread ALAN GAULD


By the way I have this piece of code using elementTree standard module 
>and according to Alan this is bad code I guess: 
>
>
Which just proves there are no absolute rules in programming :-)

try: devdb.setDescription(dev.attrib['description'])
>except KeyError: pass
>try: devdb.setSymbolName(dev.attrib['symbolName'])
>except KeyError: pass
>try: 
devdb.setSymbolPinOrderMappingList(dev.attrib['symbolPinOrderMappingList'])
>except KeyError: pass
>try: devdb.setLayoutName(dev.attrib['layoutName'])
>except KeyError: pass
>try: devdb.setLayoutType(dev.attrib['layoutType'])
>except KeyError: pass
>Since you just use pass to ignore the error then you are kind 
of forced to do it this way. Its not bad each statement has to 
be treated individually, it is not a block where all the statements 
must pass or fail as a unit.

> Do you have an alternative or my way is ok?

This would also be a valid case for an if/else check but 
in readability terms I think try/except still wins because 
the handler is only a pass. If it were more complex I'd 
probably opt for if/else.


I know there is no special case which is enough special to break the rule 
;o)
>I'm not sure I agree. In programming you can usually find a special case 
that validly breaks any "rule"! Even "Don't use goto!" :-)

HTH,

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


Re: [Tutor] Try except really better than if?

2011-01-10 Thread Karim


Thanks Alan this reassures me!

Regards
Karim

On 01/10/2011 10:39 AM, ALAN GAULD wrote:


By the way I have this piece of code using elementTree standard
module
and according to Alan this is bad code I guess:

Which just proves there are no absolute rules in programming :-)

*try: devdb.setDescription(dev.attrib['description'])
except KeyError: pass
try: devdb.setSymbolName(dev.attrib['symbolName'])
except KeyError: pass
try:
devdb.setSymbolPinOrderMappingList(dev.attrib['symbolPinOrderMappingList'])
except KeyError: pass
try: devdb.setLayoutName(dev.attrib['layoutName'])
except KeyError: pass
try: devdb.setLayoutType(dev.attrib['layoutType'])
except KeyError: pass
*

Since you just use pass to ignore the error then you are kind
of forced to do it this way. Its not bad each statement has to
be treated individually, it is not a block where all the statements
must pass or fail as a unit.

> Do you have an alternative or my way is ok?

This would also be a valid case for an if/else check but
in readability terms I think try/except still wins because
the handler is only a pass. If it were more complex I'd
probably opt for if/else.

I know there is no special case which is enough special to break
the rule ;o)

I'm not sure I agree. In programming you can usually find a special case
that validly breaks any "rule"! Even "Don't use goto!" :-)

HTH,

Alan G.



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


Re: [Tutor] Try except really better than if?

2011-01-10 Thread Steven D'Aprano

Karim wrote:


Thank you Steven, Modulok and Alan for your precious and detailed 
explanations!


I understood that I must not overuse try-except statement and usually 
when the exception could happen exceptionally.
By the way I have this piece of code using elementTree standard module 
and according to Alan this is bad code I guess:


*try: devdb.setDescription(dev.attrib['description'])
except KeyError: pass

[...]

Whenever you have very similar code repeated many times, you should 
consider factoring out the common code into a helper function. Something 
like this:


def try_or_pass(key):
attr_name = 'set' + key[0].upper() + key[1:]
try:
getattr(devb, attr_name)(dev.attrib[key])
except KeyError:
pass

try_or_pass('description')
try_or_pass('symbolName')
etc.



--
Steven

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


Re: [Tutor] Try except really better than if?

2011-01-10 Thread Karim


Steven many thanks for this useful hint!
I will modify my code.

Many thanks!
Regards
Karim

On 01/10/2011 11:32 AM, Steven D'Aprano wrote:

Karim wrote:


Thank you Steven, Modulok and Alan for your precious and detailed 
explanations!


I understood that I must not overuse try-except statement and usually 
when the exception could happen exceptionally.
By the way I have this piece of code using elementTree standard 
module and according to Alan this is bad code I guess:


*try: devdb.setDescription(dev.attrib['description'])
except KeyError: pass

[...]

Whenever you have very similar code repeated many times, you should 
consider factoring out the common code into a helper function. 
Something like this:


def try_or_pass(key):
attr_name = 'set' + key[0].upper() + key[1:]
try:
getattr(devb, attr_name)(dev.attrib[key])
except KeyError:
pass

try_or_pass('description')
try_or_pass('symbolName')
etc.





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


Re: [Tutor] Try except really better than if?

2011-01-10 Thread Steven D'Aprano

Alan Gauld wrote:


However, using exceptions like if/else blocks is bad practice.


I'm afraid I disagree strongly with that!


You need to use them like a commit in SQL - to protect a whole
block of code. Putting try/except around every line of code
defeats the purpose, wrap atomic blocks of code not the
individual lines.


Wrapping an atomic block of code, so long as it actually *can* be 
treated as atomic (including backing out any changes if it fails), is a 
good use of try...except. But otherwise, this is risky advice. Take your 
example:



try:
  something
  something else
  another
  the last
except Error1: # do something
except Error2: # do something
except Error3: # do something
finally: # tidy up



Provided the entire try block needs to be treated as a single operation 
(in which case, why isn't it a function?) then that's not too bad. But 
the risk comes from people who wrap large blocks of code *without* 
making them atomic transactions:


try:
get_job_id()
query_database()
send_results()
push_ticket()
update_counter()
except KeyError:
print "job failed"


And now an error in push_ticket means that the counter fails to be 
updated even though the results were sent. Problems occur.


The try block must contain ONE operation. It doesn't matter if the 
operation is a simple, atomic operation:


try:
y = x + 1
except...

or a large, complex transaction, so long as it can safely be treated as 
a single operation. That is, the individual sub-tasks should have no 
side-effects, or they must be backed out off on failure.


The other problem is that large try blocks can mask bugs. Here's my 
example again:


try:
get_job_id()
query_database()
send_results()
push_ticket()
update_counter()
except KeyError:
print "job failed"


The idea being that get_job_id or query_database might raise KeyError. 
But update_counter should never raise KeyError. If it does, that 
indicates a bug in update_counter, which will then be masked by the 
except as a normal error in processing. This would be better:


try:
get_job_id()
query_database()
except KeyError:
print "job failed"
else:
send_results()
push_ticket()
update_counter()


Now the else block is only executed if there is no KeyError, and any 
exceptions in those three will be detected and not masked.


Of course, you can then wrap the entire code block in another 
try...except, try...else or try...finally block. Something like this 
perhaps?



try:
try:
get_job_id()
query_database()
except KeyError:
print "job failed"
else:  # no exception caught
send_results()
push_ticket()
update_counter()
failed = True
finally:
if transaction_succeeded():
commit_transaction()
else:
rollback()


And now you are beginning to see why databases are so complicated.



is better to maintain than

try: something
except Error1: # do something
try: something else
except Error2: # do something
try: another
except Error1: # and again
try: the last
except Error3: do it
tidy up



That's what you have to do if something, something else, etc. need to be 
treated as independent operations that have to be done regardless of the 
success or failure of those that come before. Otherwise:


try:
something
try:
something_else
try:
another
except Error1:  ...
except Error2:  ...
except Error1: ...


It has been said that error handling is ten times harder than handling 
the rest of your code.




--
Steven

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


Re: [Tutor] Checkbox problem in Tkinter

2011-01-10 Thread Peter Otten
ANKUR AGGARWAL wrote:

> and i got the output as -
> [image: Screenshot.png]

The image doesn't survive.
 
> When i take the var as of string variable type i am  unable to edit the
> checkbox. It comes slected predefined and the widget in kindof Invisible
> and
> u can say uneditable. Can anybody tell me whats i am  doing wrong in
> this??? Its works fine if i take the var variable as the integer variable.
> I can deselect and select in that case and it gives me the desired result
> but in string case i am unable to do so as checkbox is invisible type.
> I am using Python 2.6

I can't reproduce that behaviour. The widget appears greyed initially, but 
is still editible. You could try to initialise the StringVar with onvalue or 
offvalue:

> from Tkinter import *
> root=Tk()
> var=StringVar()

  var.set("")

> c=Checkbutton(root,text="hello",variable=var,onvalue="",
> offvalue="")
> c.pack()
> root.mainloop()


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


Re: [Tutor] Checkbox problem in Tkinter

2011-01-10 Thread Peter Otten
Alan Gauld wrote:

> 
> "ANKUR AGGARWAL"  wrote
> 
>> from Tkinter import *
>> root=Tk()
>> var=StringVar()
>> 
c=Checkbutton(root,text="hello",variable=var,onvalue="",offvalue="")
>> c.pack()
>> root.mainloop()
> 
> FWIW I get a different problem, namely that the var does not seem
> to get updated nor does changling the var seem to alter the buuttons
> state. But at least the button displays OK with 'hello' in the label
> and
> I can select/deselect it with the mouse. its just the change to the
> variable that is broken.
> If I write an explicit event handler:
> 
> def f():
>   var = '' if var == '' else ''
> 
> Then var changes OK. Here is my code(from Pythonwin):
> 
 def f(): global var; var = 'on' if var == 'off' else 'off';print
 var
> ...
 top = Tk()
 var = StringVar()
 c = Checkbutton(top,text='txt', variable=var, onvalue='on',
 offvalue='off', command=f)
 c.pack()
 top.mainloop()
> off
> on
> off
> on
> off
> on

I think that is confusing. Tkinter is not supposed to rebind the global name 
'var', it invokes its set() method. Try

from Tkinter import *

root = Tk()
var = StringVar()

def command():
print var.get()

cb = Checkbutton(root, text="yadda", onvalue="on", offvalue="off", 
variable=var, command=command)
cb.pack()
root.mainloop()

You can also monitor changes to var's value directly:

from Tkinter import *

root = Tk()
var = StringVar()

def show(*args):
print var.get()
var.trace_variable('w', show)
cb = Checkbutton(root, text="yadda", onvalue="on", offvalue="off", 
variable=var)
cb.pack()
root.mainloop()



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


Re: [Tutor] Checkbox problem in Tkinter

2011-01-10 Thread Peter Otten
ANKUR AGGARWAL wrote:

> Hey I write this code up
> 
> from Tkinter import *
> root=Tk()
> var=StringVar()
> 
c=Checkbutton(root,text="hello",variable=var,onvalue="",offvalue="")
> c.pack()
> root.mainloop()
> 
> and i got the output as -
> [image: Screenshot.png]
> 
> When i take the var as of string variable type i am  unable to edit the
> checkbox. It comes slected predefined and the widget in kindof Invisible
> and
> u can say uneditable. Can anybody tell me whats i am  doing wrong in
> this??? Its works fine if i take the var variable as the integer variable.
> I can deselect and select in that case and it gives me the desired result
> but in string case i am unable to do so as checkbox is invisible type.
> I am using Python 2.6
> Thanks In Advance
> Ankur Aggarwal

The variable appears greyed out because initially var.get() == "", see

http://www.tcl.tk/man/tcl8.5/TkCmd/checkbutton.htm#M-tristatevalue


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


[Tutor] about import statement

2011-01-10 Thread arun kumar
Hi Friends,

I'm Arun Kumar from India, Just a month ago i started learning
programming .learned some basics of python. I'm really enjoying
programming in python.

I have some doubts in python. When we write programs,we write some
import statements at the beginning of the code. how to know that we
should import something. How do we know that certain classes are in
particular module?

Thanks

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


Re: [Tutor] about import statement

2011-01-10 Thread bob gailer

On 1/10/2011 7:58 AM, arun kumar wrote:

Hi Friends,

I'm Arun Kumar from India, Just a month ago i started learning
programming .learned some basics of python. I'm really enjoying
programming in python.

I have some doubts in python. When we write programs,we write some
import statements at the beginning of the code. how to know that we
should import something. How do we know that certain classes are in
particular module?
Python comes with basic functionality built-in. In addition there are 
many modules included in the Python distribution to supply additional 
functionality. See the Global Module Index in the Documentation. 
Unfortunately the list is large - and many of the modules are very 
specialized.


I suggest reading (at minimum) the descriptions for collections, copy, 
decimal, exceptions, glob, itertools, math, operator, os, pickle (and 
shelve), re, shutil, sys, time.


In addition there are many many other packages for extending Python that 
are not in the distribution that add more modules.


You can also write your own modules. This is a way to
- break a complex program into smaller pieces (that often can be 
independently tested)

- create common code to be used by more than one main program.

HTH.

Please return with more questions.

--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] about import statement

2011-01-10 Thread Max Countryman
On Jan 10, 2011, at 7:58 AM, arun kumar wrote:

> how to know that we
> should import something. How do we know that certain classes are in
> particular module?

You know to import a module if you need part of that module. Perhaps you need a 
class or function defined in the module.

There are several ways to see what a module provides. The documentation is 
usually a good place to start. You can also use dir(), e.g. import foo; 
dir(foo).

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


[Tutor] Equality of numbers and Strings

2011-01-10 Thread Karim


Hello All,

I am not a beginner in Python language but I discovered a hidden 
property of immutable elements as Numbers and Strings.


s ='xyz'
>>> t = str('xyz')

>>> id(s) == id(t)
True

Thus if I create 2 different instances of string if the string is 
identical (numerically).
I get the same object in py db. It could be evident but if I do the same 
(same elements) with a list it
will not give the same result. Is-it because of immutable property of 
strings and numbers?


Regards
Karim

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


Re: [Tutor] Equality of numbers and Strings

2011-01-10 Thread Emile van Sebille

On 1/10/2011 8:07 AM Karim said...


Hello All,

I am not a beginner in Python language but I discovered a hidden
property of immutable elements as Numbers and Strings.

s ='xyz'
 >>> t = str('xyz')

 >>> id(s) == id(t)
True

Thus if I create 2 different instances of string if the string is
identical (numerically).


well, not predictably unless you understand the specifics of the 
implementation you're running under.



>>> from string import letters
>>> longstring = letters*100
>>> otherstring = letters*100
>>> id(longstring)
12491608
>>> id (otherstring)
12100288
>>> shortstring = letters[:]
>>> id(letters)
11573952
>>> id(shortstring)
11573952
>>>



I get the same object in py db. It could be evident but if I do the same
(same elements) with a list it
will not give the same result. Is-it because of immutable property of
strings and numbers?



It has to do with Interning -- see eg
  http://docs.python.org/library/functions.html#intern

Generally, the shorter strings are interned to speed up dictionary 
access.  At this point, I'd characterize the coincidence of id()s as 
more of an implementation detail side effect than anything else.


Emile

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


Re: [Tutor] Equality of numbers and Strings

2011-01-10 Thread bob gailer

On 1/10/2011 11:07 AM, Karim wrote:


Hello All,

I am not a beginner in Python language but I discovered a hidden 
property of immutable elements as Numbers and Strings.


s ='xyz'
>>> t = str('xyz')

>>> id(s) == id(t)
True

Thus if I create 2 different instances of string if the string is 
identical (numerically).


Python "interns" certain literal strings - so a 2nd attempt to create 
'xyz' will refer back to the original object.


I don't know all the rules - but the following program never prints n:

for n in range(1,1):
s = eval("'" + 'wrtnjasdflkasjj'*n + "'")
t = eval("'" + 'wrtnjasdflkasjj'*n + "'")
if id(s) != id(t):
print n; break

whereas if I insert a ";" in the literal the program prints 1!

Also note str() returns the argument object unchanged.


--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] about import statement

2011-01-10 Thread Emile van Sebille

On 1/10/2011 4:58 AM arun kumar said...

Hi Friends,

I'm Arun Kumar from India, Just a month ago i started learning
programming .learned some basics of python. I'm really enjoying
programming in python.

I have some doubts in python. When we write programs,we write some
import statements at the beginning of the code. how to know that we
should import something. How do we know that certain classes are in
particular module?


I found effbot's guide to the standard library helpful -- and although 
it's nor current, you'll still get a good idea of where things are at 
and how to use them.  See http://effbot.org/zone/librarybook-index.htm


Also, experiment with help() from the python prompt.  Once in the help 
system, type in 'modules' to see a list of installed available modules 
to explore, or a module name for more info on that module.


HTH,

Emile




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


Re: [Tutor] Equality of numbers and Strings

2011-01-10 Thread bob gailer

On 1/10/2011 11:51 AM, Emile van Sebille wrote:


well, not predictably unless you understand the specifics of the 
implementation you're running under.



>>> from string import letters
>>> longstring = letters*100
>>> otherstring = letters*100
>>> id(longstring)
12491608
>>> id (otherstring)
12100288
>>> shortstring = letters[:]
>>> id(letters)
11573952
>>> id(shortstring)
11573952
>>>

In my experiment I found that using * to replicate gave different 
results than using the exact literal. That is why in the program I 
posted I used the equivalent of eval("'" + letters*n + "'") which gives 
different results than eval("letters*n")!


[snip]

--
Bob Gailer
919-636-4239
Chapel Hill NC

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


Re: [Tutor] Equality of numbers and Strings

2011-01-10 Thread wesley chun
On Mon, Jan 10, 2011 at 8:54 AM, bob gailer  wrote:

> On 1/10/2011 11:07 AM, Karim wrote:
>
>>
>> s ='xyz'
>> >>> t = str('xyz')
>>
>> >>> id(s) == id(t)
>> True
>>
>> Thus if I create 2 different instances of string if the string is
>> identical (numerically).
>>
>
> Python "interns" certain literal strings - so a 2nd attempt to create 'xyz'
> will refer back to the original object.
>


i haven't researched all the rules for strings either, but from my
understanding, they're short(er) strings which are used often enough to
warrant interning.

the (current) rule for ints is: range(-5, 257). i say current because before
2.5, it was range(-1, 101). no one bothered to tell me when i updated Core
Python to a 2nd ed. good thing i checked before it went to press! :P

note that floats are also immutable, but they're never interned, so you'll
never get the same one twice unless you're really referring to the same
object. same goes for complex, etc. interning is strictly for commonly-used
small ints and short strings.

cheers,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Equality of numbers and Strings

2011-01-10 Thread Emile van Sebille

On 1/10/2011 9:23 AM bob gailer said...

On 1/10/2011 11:51 AM, Emile van Sebille wrote:


well, not predictably unless you understand the specifics of the
implementation you're running under.


>>> from string import letters
>>> longstring = letters*100
>>> otherstring = letters*100
>>> id(longstring)
12491608
>>> id (otherstring)
12100288
>>> shortstring = letters[:]
>>> id(letters)
11573952
>>> id(shortstring)
11573952
>>>


In my experiment I found that using * to replicate gave different
results than using the exact literal. That is why in the program I
posted I used the equivalent of eval("'" + letters*n + "'") which gives
different results than eval("letters*n")!

[snip]




Hence, not predictably.

I also found it particularly interesting that an explicit copy didn't:
  shortstring = letters[:]

Emile


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


Re: [Tutor] Equality of numbers and Strings

2011-01-10 Thread Stefan Behnel

Emile van Sebille, 10.01.2011 18:42:

On 1/10/2011 9:23 AM bob gailer said...

On 1/10/2011 11:51 AM, Emile van Sebille wrote:


well, not predictably unless you understand the specifics of the
implementation you're running under.


>>> from string import letters
>>> longstring = letters*100
>>> otherstring = letters*100
>>> id(longstring)
12491608
>>> id (otherstring)
12100288
>>> shortstring = letters[:]
>>> id(letters)
11573952
>>> id(shortstring)
11573952
>>>


In my experiment I found that using * to replicate gave different
results than using the exact literal. That is why in the program I
posted I used the equivalent of eval("'" + letters*n + "'") which gives
different results than eval("letters*n")!


Hence, not predictably.

I also found it particularly interesting that an explicit copy didn't:
shortstring = letters[:]


There's no need to copy an immutable object.

Stefan

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


Re: [Tutor] Equality of numbers and Strings

2011-01-10 Thread Stefan Behnel

Karim, 10.01.2011 17:07:

I am not a beginner in Python language but I discovered a hidden property
of immutable elements as Numbers and Strings.

s ='xyz'
 >>> t = str('xyz')

 >>> id(s) == id(t)
True

Thus if I create 2 different instances of string if the string is
identical (numerically). I get the same object in py db. It could be
evident but if I do the same (same elements) with a list it will not
give the same result. Is-it because of immutable property of strings and
numbers?


AFAIR, all string literals in a module are interned by the CPython 
compiler, and short strings that look like identifiers are also interned 
(to speed up dictionary lookups, e.g. for function names). So you will get 
identical objects in these cases, although it's not a good idea to rely on 
this as it's an implementation detail of the runtime.


And the second thing that you can observe here is that str() never copies a 
string you pass in, which is reasonable behaviour for immutable objects.




Thus if I create 2 different instances of string if the string is
identical (numerically).


There's no such thing as "numerically identical" strings. It's enough to 
say that they are identical as opposed to equal.


Stefan

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


Re: [Tutor] Try except really better than if?

2011-01-10 Thread Alan Gauld

"Steven D'Aprano"  wrote

Wrapping an atomic block of code, so long as it actually *can* be 
treated as atomic (including backing out any changes if it fails), 
is a good use of try...except.


That's exactly what I meant by atomic. A (smallish) group of 
instructions
that must be treated as a group, if any one fails the whole block 
fails

and must be backed out or aborted.

Provided the entire try block needs to be treated as a single 
operation (in which case, why isn't it a function?)


The point about the function is good and the try/except can live
within the function.

a single operation. That is, the individual sub-tasks should have no 
side-effects, or they must be backed out off on failure.


Absolutely. That is the key criterion.

It has been said that error handling is ten times harder than 
handling the rest of your code.


Yep, and usually takes up about ten times as much code.
I once analyzed a largish project - about 1.5 million lines of C++.
Only ~250k lines were actual funcionality, the rest were split between
GUI (before GUI Builders etc) and error handling (and some logging
for our IT department's benefit). I can't recall the split between GUI
and errors but it was scary to see how little was real functonal 
code...
( This didn't include any SQL or script files but it was before the 
days

of stored procedures so most of the SQL was probably ermbedded
in the C++ anyway).


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] Checkbox problem in Tkinter

2011-01-10 Thread Alan Gauld


"Peter Otten" <__pete...@web.de> wrote



I can select/deselect it with the mouse. its just the change to the
variable that is broken.


This was the problem using the Stringvar.



Then var changes OK. Here is my code(from Pythonwin):


def f(): global var; var = 'on' if var == 'off' else 'off';print
var

...

top = Tk()
var = StringVar()
c = Checkbutton(top,text='txt', variable=var, onvalue='on',
offvalue='off', command=f)
c.pack()
top.mainloop()

off
on


I think that is confusing. Tkinter is not supposed to rebind the 
global name

'var', it invokes its set() method. Try


Yes, my bad, I should have removed the StringVar assigment it was
just a carryover from the previous attempt. The problem was that
the StringVar was never changing when the control was clicked.
This was my attempt to create a manual solution that avoided the
automated StringVar approach.


def command():
   print var.get()


This raises an interesting point though. I was printing var - which
never changed - I forgot about the need to go through a get()
method. Time for another experiment

Alan G. 



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


Re: [Tutor] about import statement

2011-01-10 Thread Alan Gauld

"arun kumar"  wrote


I have some doubts in python. When we write programs,we write some
import statements at the beginning of the code. how to know that we
should import something. 


Trial and error, experience and mainly reading the documentation.
You try to do something and there is no obvious direct solution in
the basic Python built-in commands and functions, so we go to 
the module library to see if anything looks useful.


Then we use dir() and help() to find out what is in the module 
and how to use it. If nothing exists in the library then we try 
Google and perhaps install a third party package.



How do we know that certain classes are in particular module?


dir(), help() and reading the documents.

Sorry, there are no easier answers, but that kind of research 
is one of the keys to programming. And sometimes you will 
probably write code that could have been done via a module

but you just didn't know it existed. I've done that lots of times!

Reading this list is a good way to discover some of the more 
obscure but useful modules available.


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] Equality of numbers and Strings

2011-01-10 Thread Karim


Many thanks Emile, Bob, Stefan, Wesley!

Now, I see now that the point is more related to implementation details 
and optimization instead of a true

property. But it could mistaken people not aware.

Regards
Karim


On 01/10/2011 06:56 PM, Stefan Behnel wrote:

Karim, 10.01.2011 17:07:
I am not a beginner in Python language but I discovered a hidden 
property

of immutable elements as Numbers and Strings.

s ='xyz'
>>> t = str('xyz')

>>> id(s) == id(t)
True

Thus if I create 2 different instances of string if the string is
identical (numerically). I get the same object in py db. It could be
evident but if I do the same (same elements) with a list it will not
give the same result. Is-it because of immutable property of strings and
numbers?


AFAIR, all string literals in a module are interned by the CPython 
compiler, and short strings that look like identifiers are also 
interned (to speed up dictionary lookups, e.g. for function names). So 
you will get identical objects in these cases, although it's not a 
good idea to rely on this as it's an implementation detail of the 
runtime.


And the second thing that you can observe here is that str() never 
copies a string you pass in, which is reasonable behaviour for 
immutable objects.




Thus if I create 2 different instances of string if the string is
identical (numerically).


There's no such thing as "numerically identical" strings. It's enough 
to say that they are identical as opposed to equal.


Stefan

___
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] __init__() - is it required?

2011-01-10 Thread Corey Richardson
On 01/09/2011 04:27 PM, Steven D'Aprano wrote:
> Corey Richardson wrote:
>> Do all classes need an __init__() method? I have classes that look much
>> like this one starts out:
>>
>> class GenerateXML(object):
>> """Defines methods to be inherited for StaticXML and AnimationXML"""
>> def __init__(self):
>> pass
>>
>> I would rather not do that. Code without it runs fine, but will there be
>> any negative consequences down the road? Does object define an __init__
>> method for me?
> 
> You don't need to define an __init__ if you don't need one. A 
> placeholder __init__ that does nothing, as above, is a waste of space.
> 
> object includes an __init__ method that not only does nothing, but 
> ignores any arguments you pass to it:
> 
>  >>> object.__init__
> 
>  >>> object.__init__(1, 2, 3)
>  >>>
> 
> In Python 2.x, you can have "old-style" classes that don't inherit from 
> object. They too don't need an __init__:
> 
>  >>> class Old:  # *don't* inherit from object
> ... pass
> ...
>  >>> o = Old()
>  >>>
> 
> 

Thank you very much Alan and Steven!

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


[Tutor] Missing Data in Txt Files

2011-01-10 Thread Benson, Randall
Hello,

Does anyone have a program that will read txt file data and insert -
or similar for missing data?  I have 10minute data and there are hour
chunks that are missing that need a missing data insert for that missing
hour but not the 10min period.  The txt file has a date column (yymmdd),
a time (hhmm) column and the rest are data columns shown below.  See
column 1 below with i

080618 1000  4.62  7.00 227.0  -3.38  -3.15   0.00 .99 .99  0.91
080618 1410  5.19  7.30 232.0  -4.09  -3.20   0.00 .99 .99  1.03
 
Muchas gracias,



Randall P. Benson, PhD
Global Technical Division/Energy Resources
O:  503-796-7129
M: 971-227-2477


-Original Message-
From: tutor-bounces+randall.benson=iberdrolaren@python.org
[mailto:tutor-bounces+randall.benson=iberdrolaren@python.org] On
Behalf Of Corey Richardson
Sent: Monday, January 10, 2011 1:25 PM
To: tutor@python.org
Subject: Re: [Tutor] __init__() - is it required?

On 01/09/2011 04:27 PM, Steven D'Aprano wrote:
> Corey Richardson wrote:
>> Do all classes need an __init__() method? I have classes that look
much
>> like this one starts out:
>>
>> class GenerateXML(object):
>> """Defines methods to be inherited for StaticXML and
AnimationXML"""
>> def __init__(self):
>> pass
>>
>> I would rather not do that. Code without it runs fine, but will there
be
>> any negative consequences down the road? Does object define an
__init__
>> method for me?
> 
> You don't need to define an __init__ if you don't need one. A 
> placeholder __init__ that does nothing, as above, is a waste of space.
> 
> object includes an __init__ method that not only does nothing, but 
> ignores any arguments you pass to it:
> 
>  >>> object.__init__
> 
>  >>> object.__init__(1, 2, 3)
>  >>>
> 
> In Python 2.x, you can have "old-style" classes that don't inherit
from 
> object. They too don't need an __init__:
> 
>  >>> class Old:  # *don't* inherit from object
> ... pass
> ...
>  >>> o = Old()
>  >>>
> 
> 

Thank you very much Alan and Steven!

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

Please be advised that email addresses for Iberdrola Renewables personnel have 
changed to first.l...@iberdrolaren.com effective Aug. 16, 2010.  Please make a 
note.  Thank you.

This message is intended for the exclusive attention of the recipient(s) 
indicated.  Any information contained herein is strictly confidential and 
privileged.  If you are not the intended recipient, please notify us by return 
e-mail and delete this message from your computer system. Any unauthorized use, 
reproduction, alteration, filing or sending of this message and/or any attached 
files may lead to legal action being taken against the party(ies) responsible 
for said unauthorized use. Any opinion expressed herein is solely that of the 
author(s) and does not necessarily represent the opinion of the Company. The 
sender does not guarantee the integrity, speed or safety of this message, and 
does not accept responsibility for any possible damage arising from the 
interception, incorporation of viruses, or any other damage as a result of 
manipulation.


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


Re: [Tutor] Missing Data in Txt Files

2011-01-10 Thread Emile van Sebille

On 1/10/2011 4:10 PM Benson, Randall said...

Hello,

Does anyone have a program that will read txt file data and insert -
or similar for missing data?  I have 10minute data and there are hour
chunks that are missing that need a missing data insert for that missing
hour but not the 10min period.  The txt file has a date column (yymmdd),
a time (hhmm) column and the rest are data columns shown below.  See
column 1 below with i

080618 1000  4.62  7.00 227.0  -3.38  -3.15   0.00 .99 .99  0.91
080618 1410  5.19  7.30 232.0  -4.09  -3.20   0.00 .99 .99  1.03



Hi Randall,

First, please start a new thread next time -- you replied to an existing 
thread which can cause your post to go unnoticed...


I doubt anyone will have a specific program to do what you're asking, 
and for most of us writing this is what we'd expect to do.


I think I'd put the data into a dictionary and access the keys in a loop 
with a default provided for missing keys.  Something along the lines of:


lines = open('data/file/name').readlines()
D = dict((line{:11),line) for line in lines)

for timestamp in timestampgenerator:
data = D.get(timestamp,-)
...

Of course it all depends

Emile


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


Re: [Tutor] Missing Data in Txt Files

2011-01-10 Thread Alan Gauld


"Benson, Randall"  wrote

hour but not the 10min period.  The txt file has a date column 
(yymmdd),

a time (hhmm) column and the rest are data columns shown below.  See
column 1 below with i


Not sure what the last sentence merans? Was there supposed to
be more? Or what is the 'i' referred to?

080618 1000  4.62  7.00 227.0  -3.38  -3.15   0.00 .99 .99 
0.91
080618 1410  5.19  7.30 232.0  -4.09  -3.20   0.00 .99 .99 
1.03


I'm not sure what this is telling me. Is there an example of such
missing data here? Does 0.00 mean its missing? Or is it something 
else?


What you want should be possible but we need a much clearer
specification of the problem.

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] Missing Data in Txt Files

2011-01-10 Thread bob gailer

On 1/10/2011 7:10 PM, Benson, Randall wrote:

Hello,

Does anyone have a program that will read txt file data and insert -
or similar for missing data?  I have 10minute data and there are hour
chunks that are missing that need a missing data insert for that missing
hour but not the 10min period.  The txt file has a date column (yymmdd),
a time (hhmm) column and the rest are data columns shown below.  See
column 1 below with i

080618 1000  4.62  7.00 227.0  -3.38  -3.15   0.00 .99 .99  0.91
080618 1410  5.19  7.30 232.0  -4.09  -3.20   0.00 .99 .99  1.03

Muchas gracias,


I agree with Alan. We need more detail.

Why are you asking this question on the Python Tutor list?

I presume you are using Python.

We prefer to help you as you show us effort. Do you know enough Python 
to write a program that reads a file and creates another?


I suggest you start with that, and also give us enough additional 
details so we fully understand what you want.


Sample input - sample output would help a lot.

--
Bob Gailer
919-636-4239
Chapel Hill NC

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