Re: [Tutor] Populating a list

2012-10-22 Thread Saad Javed
l.extend does work. Thanks!

On Monday, October 22, 2012, Saad Javed wrote:

 My program downloads multiple entry values from the net. I'm trying to
 combine them in a list in a particular sequence.

 l = []
 feed1 = urllib2.urlopen(rssPage1)
 tree1 = etree.parse(feed1)
 x = tree1.xpath(/rss/channel/item/title/text())
 y = tree1.xpath(/rss/channel/item/pubDate/text())
 z = tree1.xpath(/rss/channel/item/link/text())
 for e, f, g in zip(x, y, z):
  l.append([e, f, g])
 print l

 The problem I'm facing is that the values don't combine into a single list
 (l). It keeps printing multiple lists with three values e, f, g as the
 xml tree is parsed.


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


[Tutor] Creating a list from other lists

2012-10-22 Thread Saad Javed
Hi,

I'm trying to create a list (L) from items of different lists (a, b, c) but
in a specific order (L = [[a1, b1, c1], [a2, b2, c2]...etc])
L = []
a = [1, 2, 3, 4]
b = ['a', 'b', 'c', 'd']
c = [2009, 2010, 2011, 2012]

for x, y , z in zip(a, b, c):
L.extend([x, y, z])
print L

But this outputs:
[[1, 'a', 2009]]
[[1, 'a', 2009], [2, 'b', 2010]]
[[1, 'a', 2009], [2, 'b', 2010], [3, 'c', 2011]]
[[1, 'a', 2009], [2, 'b', 2010], [3, 'c', 2011], [4, 'd', 2012]]

I just want L = [[1, 'a', 2009], [2, 'b', 2010], [3, 'c', 2011], [4, 'd',
2012]]

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


Re: [Tutor] Creating a list from other lists

2012-10-22 Thread Walter Prins
Hi Saad,

On 22 October 2012 11:21, Saad Javed sbja...@gmail.com wrote:
 Hi,

 I'm trying to create a list (L) from items of different lists (a, b, c) but
 in a specific order (L = [[a1, b1, c1], [a2, b2, c2]...etc])
 L = []
 a = [1, 2, 3, 4]
 b = ['a', 'b', 'c', 'd']
 c = [2009, 2010, 2011, 2012]

 for x, y , z in zip(a, b, c):
 L.extend([x, y, z])
 print L

 But this outputs:
 [[1, 'a', 2009]]
 [[1, 'a', 2009], [2, 'b', 2010]]
 [[1, 'a', 2009], [2, 'b', 2010], [3, 'c', 2011]]
 [[1, 'a', 2009], [2, 'b', 2010], [3, 'c', 2011], [4, 'd', 2012]]

 I just want L = [[1, 'a', 2009], [2, 'b', 2010], [3, 'c', 2011], [4, 'd',
 2012]]

You've already asked essentially this question on another thread -- in
general please don't start new threads for the same question but
continue the discussion on the original question for the sake of
continuity and avoiding wasting people's time.  (New readers of the
new question may not be aware of the previous discussion, and may
expend time and energy addressing issues which have already been
discussed in the previous question.)

As for your problem: You're printing the list every iteration of the
loop which is why your output looks the way it does.   Instead put
your print statement after the loop and you'll see the list you get
after the loop is in fact what you say you want.

However, that doesn't actually solve your problem, because you're
putting the input data into the lists in sorted order already.  You
should jumble up your input data to ensure you also solve the sorting
aspect of this problem (or use the input data from your original
problem which was jumbled up enough already.)

Hint, to deal with sorting your output list, refer to the list.sort()
method and the key   parameter.  See also the Sorting HowTo on the
PythonInfo wiki by Raymond Hettinger:
http://wiki.python.org/moin/HowTo/Sorting/

Hope is enough to get you going,

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


Re: [Tutor] Creating a list from other lists

2012-10-22 Thread Steven D'Aprano

On 22/10/12 21:21, Saad Javed wrote:

Hi,

I'm trying to create a list (L) from items of different lists (a, b, c) but
in a specific order (L = [[a1, b1, c1], [a2, b2, c2]...etc])
L = []
a = [1, 2, 3, 4]
b = ['a', 'b', 'c', 'd']
c = [2009, 2010, 2011, 2012]

for x, y , z in zip(a, b, c):
L.extend([x, y, z])
print L


This is not your code, because that gives a SyntaxError. Where is
the indentation? Indentation is required in Python, if you leave it
out, your code will not work correctly. You should have either:

# Option 1
for x, y , z in zip(a, b, c):
L.extend([x, y, z])
print L


which will extend the list four times, and print the list four times,
once each time through the loop. Or:


# Option 2
for x, y , z in zip(a, b, c):
L.extend([x, y, z])

print L  # this is not indented, so it is outside the loop



Now the list only gets printed once, after the for loop has
completely finished, and you don't see the intermediate results.




But this outputs:
[[1, 'a', 2009]]
[[1, 'a', 2009], [2, 'b', 2010]]
[[1, 'a', 2009], [2, 'b', 2010], [3, 'c', 2011]]
[[1, 'a', 2009], [2, 'b', 2010], [3, 'c', 2011], [4, 'd', 2012]]

I just want L = [[1, 'a', 2009], [2, 'b', 2010], [3, 'c', 2011], [4, 'd',
2012]]


Then don't print the list four times, only print it once.




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


Re: [Tutor] Creating a list from other lists

2012-10-22 Thread eryksun
On Mon, Oct 22, 2012 at 6:37 AM, Steven D'Aprano st...@pearwood.info wrote:
 On 22/10/12 21:21, Saad Javed wrote:

 for x, y , z in zip(a, b, c):
 L.extend([x, y, z])
 print L

 This is not your code, because that gives a SyntaxError. Where is
 the indentation? Indentation is required in Python, if you leave it
 out, your code will not work correctly.

It's an HTML post. Using these styled span tags never translates
well to the text/plain section.

div

for x, y , z in zip(a, b, c):

/div
div
span class=Apple-tab-span style=white-space:pre   /span

L.extend([x, y, z])

/div
div
span class=3DApple-tab-span style=3Dwhite-space:pre   /span

print L

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


Re: [Tutor] Creating a list from other lists

2012-10-22 Thread Walter Prins
Hi Saad,

On 22 October 2012 11:37, Steven D'Aprano st...@pearwood.info wrote:
 On 22/10/12 21:21, Saad Javed wrote:
 I'm trying to create a list (L) from items of different lists (a, b, c)
 but
 in a specific order (L = [[a1, b1, c1], [a2, b2, c2]...etc])
 L = []
 a = [1, 2, 3, 4]
 b = ['a', 'b', 'c', 'd']
 c = [2009, 2010, 2011, 2012]

 for x, y , z in zip(a, b, c):
 L.extend([x, y, z])
 print L


 This is not your code, because that gives a SyntaxError. Where is
 the indentation? Indentation is required in Python, if you leave it
 out, your code will not work correctly. You should have either:

Just to note: For me your (Saad's) indentation showed perfectly fine
on GMail.  I'm note sure why Steven didn't see it (I think he reads
only plaintext email), so I'd guess perhaps your email included both
HTML and plain text parts and the plain text part perhaps had the
indentation stripped out and the HTML did not.  Anyway point being,
it's best to post plain text if you're emailing unless you absolutely
must use HTML, certainly this is the best way for this mailing list.

Regards,

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


[Tutor] Which is better Practice and why

2012-10-22 Thread Matthew Ngaha
In many of the tutorial examples ive come across, the main code's program
is never at the top level, but always in a function of some sort. i
understand why but, there is always a different way used to access the main
code, i want to know which is the best.


main()
 main's code

#top level
main()

they call the main program by simply calling the main function. I've also
seen a more complcated:

if __name__ == '__main__':
main()

the 2nd one usually includes a lot more code then i showed. can you please
tell me why different methods are used to access the main code? is it just
preference or is one way actually better coding practice?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Which is better Practice and why

2012-10-22 Thread Devin Jeanpierre
On Mon, Oct 22, 2012 at 7:45 AM, Matthew Ngaha chigga...@gmail.com wrote:
 the 2nd one usually includes a lot more code then i showed. can you please
 tell me why different methods are used to access the main code? is it just
 preference or is one way actually better coding practice?

The second one is used if your importable modules are also scripts
that can be executed.

That's a bad idea, because it results in the same source file being
executed twice, producing distinct classes that break typechecking. If
you have myprogram.py containing the following source code, and
execute it as a program, it will terminate with an uncaught MyError.

class MyError(Exception): pass

import myprogram
try: raise myprogram.MyError
except MyError: pass

So, in any circumstance where you would use the second one, it's
because you're in a situation where bad things are happening. So use
the first one always. And if there's code in the script you want to
share, put it in a separate module.

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


Re: [Tutor] Which is better Practice and why

2012-10-22 Thread Mark Lawrence

On 22/10/2012 12:45, Matthew Ngaha wrote:

In many of the tutorial examples ive come across, the main code's program
is never at the top level, but always in a function of some sort. i
understand why but, there is always a different way used to access the main
code, i want to know which is the best.


main()
  main's code

#top level
main()

they call the main program by simply calling the main function. I've also
seen a more complcated:

if __name__ == '__main__':
 main()

the 2nd one usually includes a lot more code then i showed. can you please
tell me why different methods are used to access the main code? is it just
preference or is one way actually better coding practice?



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



See this http://docs.python.org/tutorial/modules.html specifically 
section 6.1.1. Executing modules as scripts.


--
Cheers.

Mark Lawrence.

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


Re: [Tutor] Which is better Practice and why

2012-10-22 Thread Joel Goldstick
On Mon, Oct 22, 2012 at 7:45 AM, Matthew Ngaha chigga...@gmail.com wrote:
 In many of the tutorial examples ive come across, the main code's program is
 never at the top level, but always in a function of some sort. i understand
 why but, there is always a different way used to access the main code, i
 want to know which is the best.


 main()
  main's code

 #top level
 main()

 they call the main program by simply calling the main function. I've also
 seen a more complcated:

 if __name__ == '__main__':
 main()

Every module in python has a name.  You have probably seen code like this:

import os
import sys

os and sys are modules and their names are 'os' and 'sys'

When you write your own program in a file 'my_code.py' and then run it
by typing:

python my_code.py

The name of your program is '__main__'

So when you write:

  if __name__ == '__main__':
your code here

The code will only run when  you run the file directly.  Many times,
the functions in your file could be used in other programs.  In that
case you might have a file called my_new_code.py
In my_new_code.py you could import the other file so you could use its
functions.  Like this:

import my_code

When you import the file, it is not the __main__ code.  Its name will
be my_code.  And so the code you have in the part I marked your code
here will never run.  It only runs when you run the file directly.

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


Re: [Tutor] Which is better Practice and why

2012-10-22 Thread Matthew Ngaha
oh ok i understand it.. Thanks for the help guys
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Which is better Practice and why

2012-10-22 Thread eryksun
On Mon, Oct 22, 2012 at 7:54 AM, Devin Jeanpierre
jeanpierr...@gmail.com wrote:

 The second one is used if your importable modules are also scripts
 that can be executed.

 That's a bad idea, because it results in the same source file being
 executed twice, producing distinct classes that break typechecking.

Here's an exception to the above. On Windows, multiprocessing requires
you to gate the setup in __main__ since the module is re-imported in
each new process (win32 doesn't fork).
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Which is better Practice and why

2012-10-22 Thread Walter Prins
Devin,

On 22 October 2012 12:54, Devin Jeanpierre jeanpierr...@gmail.com wrote:
 On Mon, Oct 22, 2012 at 7:45 AM, Matthew Ngaha chigga...@gmail.com wrote:
 the 2nd one usually includes a lot more code then i showed. can you please
 tell me why different methods are used to access the main code? is it just
 preference or is one way actually better coding practice?

 The second one is used if your importable modules are also scripts
 that can be executed.

 That's a bad idea, because it results in the same source file being
 executed twice, producing distinct classes that break typechecking. If
 you have myprogram.py containing the following source code, and
 execute it as a program, it will terminate with an uncaught MyError.

 class MyError(Exception): pass

 import myprogram
 try: raise myprogram.MyError
 except MyError: pass

Why would you do this though?  Is the source of the problem not really
that you're importing a module inside itself?  Why would you generally
want to do this? Furthermore the 'if __name__ == __main__' idiom is
explicitly part of Python and generally well accepted (so it seems to
me at least), so the above seems like a fairly esoteric objection to
its use?

Thanks,

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


Re: [Tutor] Which is better Practice and why

2012-10-22 Thread Oscar Benjamin
On 22 October 2012 12:54, Devin Jeanpierre jeanpierr...@gmail.com wrote:
 On Mon, Oct 22, 2012 at 7:45 AM, Matthew Ngaha chigga...@gmail.com wrote:

Hi Devin, your context was missing the crucial part showing the 2nd one:

 they call the main program by simply calling the main function. I've also
 seen a more complcated:

 if __name__ == '__main__':
 main()

 the 2nd one usually includes a lot more code then i showed. can you please
 tell me why different methods are used to access the main code? is it just
 preference or is one way actually better coding practice?

 The second one is used if your importable modules are also scripts
 that can be executed.

 That's a bad idea, because it results in the same source file being
 executed twice, producing distinct classes that break typechecking. If
 you have myprogram.py containing the following source code, and
 execute it as a program, it will terminate with an uncaught MyError.

There is nothing wrong with having a script that can also be imported
(or a module that can also be executed). I do this often, particularly
when I have a number of related scripts in the same folder as one
another.

Python allows a .py file to represent a script or a module. Python
itself maintains no formal distinction between scripts and modules.
Adding if __name__ == __main__ allows your script/module to
determine whether it is being executed or imported and do different
things in each case.

One case where this is good is to add a test suite to a module. For
example my module defines some functions that can be imported by other
modules. It also defines some code to test that the functions it
defines are working properly. I don't want to run the tests every time
I import the module but I can run them conveniently if I put them in a
__name__ == __main__ block and then execute the module as a script
every now and then. Both the unittest and doctest modules supply
functions specifically for use in this way.

Another common case is that your module defines some functions that
are of general use but you also make it possible to run the module as
a script in order to perform some of the most common operations that
your module performs. There are several examples in the Python
standard library that do this for example pdb and cProfile.

It is also sometimes useful to define a number of scripts that are in
the same directory but share some code by importing one another. You
need the if __name__ ==__main__ block for this.

The problem that Devin is referring to only happens in certain odd
situations where the script that you run ends up importing itself
(perhaps indirectly). I have never personally had that problem though.


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


Re: [Tutor] Which is better Practice and why

2012-10-22 Thread eryksun
On Mon, Oct 22, 2012 at 9:35 AM, Oscar Benjamin
oscar.j.benja...@gmail.com wrote:

 It is also sometimes useful to define a number of scripts that are in
 the same directory but share some code by importing one another. You
 need the if __name__ ==__main__ block for this.

 The problem that Devin is referring to only happens in certain odd
 situations where the script that you run ends up importing itself
 (perhaps indirectly). I have never personally had that problem though.

Just to clarify that I'm following you, would you count the following
as a script importing itself 'indirectly'?

Assume two modules in the same directory, mod1.py and mod2.py, can
both act as the main entry point, and both import each other (assume
no circular import problem). Then if mod1.py runs as __main__ and
imports mod2, and mod2.py imports mod1, there are 2 copies of the
classes and functions defined in mod1.py. For example, there's
__main__.MyError vs mod1.MyError.

I agree there's no problem if no other module imports the module
currently running as __main__. In that case, there's nothing
technically wrong with mixing script functionality into a module that
can also be imported. Self-contained test cases are a clear example of
this.

Also, modules can import __main__, but it's not used frequently. I
count 16 cases of this in the 2.7.3 standard library, for
introspective usage such as in idlelib, cProfile, pdb, etc.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Which is better Practice and why

2012-10-22 Thread eryksun
On Mon, Oct 22, 2012 at 11:14 AM, eryksun eryk...@gmail.com wrote:

 Just to clarify that I'm following you, would you count the following
 as a script importing itself 'indirectly'?

 Assume two modules in the same directory, mod1.py and mod2.py, can
 both act as the main entry point, and both import each other (assume
 no circular import problem). Then if mod1.py runs as __main__ and
 imports mod2, and mod2.py imports mod1, there are 2 copies of the
 classes and functions defined in mod1.py. For example, there's
 __main__.MyError vs mod1.MyError.

I forgot to specify that __main__ can reference mod1 via mod2.mod1, so
my question is if this indirection via mod2 is what you meant by
importing itself 'indirectly'. Thanks.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Segmentation Fault shenanigans with wx Gui

2012-10-22 Thread Prasad, Ramit
Marco Mistroni wrote:
 
 Hello
  i found the problem. It's  calling self.list.ClearAll that causes the 
 segmentation fault.
 removing the call to  ClearAll fixed my problem , but i still want to clear 
 the list before i  load new
 data..
 could anyone assist?

I think the problem is the way you populate the data. The issue
with ClearAll is a side effect of that. See below for more information.

 
 wkr
  marco
 On Fri, Oct 19, 2012 at 11:05 PM, Marco Mistroni mmistr...@gmail.com wrote:
 Hi all
  i have written a wx GUI which downloads json data from a server, and 
 populate a listbox.
 Every time i populate a listbox, i am receiving Segmentation Faults.
 I have tried to retrieve data from the URL via separate thread, and to use 
 events, but i am still getting a
 segmentation fault
 
 could anyone assist pls?
 
 here's relevant code. I m running python on Ubuntu 10.04
 
[snip]
 
     self.list = AutoWidthListCtrl(panel)'

This mailing list is for learning Python. Support and familiarity 
with 3rd party packages is limited. You will probably be better off
asking the wxpython mailing list. Especially as the AutoWidthListCtrl
is not a widget that comes with wxpython. 

[snip]
 
     def OnResult(self, event):
     print 'onResult'
     ptf_data = event.data
     for item in ptf_data['portfolio']['items']:
         index = self.list.InsertStringItem(sys.maxint, item['ticker'])

I believe this is the source of your problem. You are using the
incorrect value as the index. If you look at documentation for
the base class ListCtrl [0][1] you will notice that the first 
argument to InsertStringItem is the insertion index. Instead you are
using the same value (sys.maxint) for all items you are inserting.
sys.maxint represents the maximum integer supported by the system
and is not relevant for what you are trying to do. Instead use an
incrementing count. 

 rows = self.list.GetItemCount()
 for index, item in enumerate( ptf_data['portfolio']['items'], rows ):
 self.list.InsertStringItem(index, item['ticker'])

 [0]: http://wiki.wxpython.org/ListControls
[1]: http://www.wxpython.org/docs/api/wx.ListCtrl-class.html 

         self.list.SetStringItem(index, 1, item['name'])
         self.list.SetStringItem(index, 2, str(item['movingAvg200']))
         self.list.SetStringItem(index, 3, str(item['movingAvg50']))
         self.list.SetStringItem(index, 4, str(item['price']))
         self.list.SetStringItem(index, 5, str(item['previous']))
         self.list.SetStringItem(index, 6, str(item['price'] - 
 item['previous']) )
         self.list.SetStringItem(index, 7, str(item['totalValue']))
         self.list.SetStringItem(index, 8, str(item['position']))
 

Do let us know if the suggestion works or not.

Ramit Prasad


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] name conventions

2012-10-22 Thread Mike McTernan
Hi there,

I am doing some online tutorials and have found two approaches to
naming things: this_is_a_name and thisIsAName.

Which one is the best practice for Python? I am a totally newbie to
programming and want to make sure I start with the most common
approach.

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


Re: [Tutor] name conventions

2012-10-22 Thread eryksun
On Mon, Oct 22, 2012 at 1:43 PM, Mike McTernan livingm...@gmail.com wrote:
 Hi there,

 I am doing some online tutorials and have found two approaches to
 naming things: this_is_a_name and thisIsAName.

Read PEP 8, specifically the section on Naming Conventions:

http://www.python.org/dev/peps/pep-0008/#naming-conventions
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] name conventions

2012-10-22 Thread Emile van Sebille

Mike McTernan wrote:

Hi there,

I am doing some online tutorials and have found two approaches to
naming things: this_is_a_name and thisIsAName.

Which one is the best practice for Python? I am a totally newbie to
programming and want to make sure I start with the most common
approach.



The official word is pep 8 -- http://www.python.org/dev/peps/pep-0008/

Emile

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


Re: [Tutor] Which is better Practice and why

2012-10-22 Thread Oscar Benjamin
On 22 October 2012 16:14, eryksun eryk...@gmail.com wrote:
 On Mon, Oct 22, 2012 at 9:35 AM, Oscar Benjamin
 oscar.j.benja...@gmail.com wrote:

 It is also sometimes useful to define a number of scripts that are in
 the same directory but share some code by importing one another. You
 need the if __name__ ==__main__ block for this.

 The problem that Devin is referring to only happens in certain odd
 situations where the script that you run ends up importing itself
 (perhaps indirectly). I have never personally had that problem though.

 Just to clarify that I'm following you, would you count the following
 as a script importing itself 'indirectly'?

Yes.

 Assume two modules in the same directory, mod1.py and mod2.py, can
 both act as the main entry point, and both import each other (assume
 no circular import problem).

They both import each other. That is a circular import and it can
create problems. My advice for this issue is not avoid importable
scripts but rather avoid circular imports (a good idea anyway).

 Then if mod1.py runs as __main__ and
 imports mod2, and mod2.py imports mod1, there are 2 copies of the
 classes and functions defined in mod1.py. For example, there's
 __main__.MyError vs mod1.MyError.

I agree that this would be problematic. However, if mod1.py and
mod2.py both import each another then neither of them is really an
independent script. There is no reason why any common code should not
be moved into a third module to avoid the circular import.

I have used importable scripts many times and never had this problem
because I have never used them with circular imports. Typically the
action of running the module as a script provides a command line
interface that does some common but useful thing with the code in that
same module (rather than code imported from other modules).

An example from a recent project: I have a module that defines
functions for interacting with a particular database. It can be
imported by scripts that perform computations based on the contents of
the database. It can also be run as a script in which case it provides
a command line interface to query/export the contents of the database.
This particular module does not import any other modules within the
same project so it will never have the circular import problem. There
are other importable scripts that depend on the database module but
they also don't use circular imports.


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


Re: [Tutor] Which is better Practice and why

2012-10-22 Thread eryksun
On Mon, Oct 22, 2012 at 2:26 PM, Oscar Benjamin
oscar.j.benja...@gmail.com wrote:

 They both import each other. That is a circular import and it can
 create problems. My advice for this issue is not avoid importable
 scripts but rather avoid circular imports (a good idea anyway).

I agree it's better to refactor common code to a separate module, but
if you search the net you'll find lots of well-intentioned advice on
how to make circular import scenarios work.

You had said define a number of scripts that are in the same
directory but share some code by [importing one another], and I
wanted to be clear about how that related to your comment about the
main module indirectly importing itself. Thanks for taking the time to
clear that up.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] newb help reading lines from csv

2012-10-22 Thread Dewhirst, Rob
import csv
ifile = open('test.csv', r)
reader = csv.reader(ifile)
for row in reader:
print row
for row in reader:
print row
ifile.close()

This is a simplified version of what I am trying to do - loop through
a CSV file twice.  Why does the second for loop not execute at all?
The first one prints the rows of the file just fine.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] newb help reading lines from csv

2012-10-22 Thread LZAntal
Hi,

On Oct 22, 2012, at 12:20 PM, Dewhirst, Rob robdewhi...@gmail.com wrote:

 import csv
 ifile = open('test.csv', r)
 reader = csv.reader(ifile)
 for row in reader:
   print row
 for row in reader:
   print row
 ifile.close()
 
 This is a simplified version of what I am trying to do - loop through
 a CSV file twice.  Why does the second for loop not execute at all?
 The first one prints the rows of the file just fine.
 _

I believe csv module uses iterator so you need to run reader.seek(0) between 
the for loops


Laszlo
http://twitter.com/LZAntal


 __
 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] newb help reading lines from csv

2012-10-22 Thread Emile van Sebille

Dewhirst, Rob wrote:

import csv
ifile = open('test.csv', r)
reader = csv.reader(ifile)
for row in reader:
print row
for row in reader:
print row
ifile.close()

This is a simplified version of what I am trying to do - loop through
a CSV file twice.  Why does the second for loop not execute at all?
The first one prints the rows of the file just fine.


The first pass also exhausts the input feed -- you'll need to rewind or 
reposition the next line pointer to the start of the file and I suspect 
the easiest way is to reopen the file.


Emile

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


Re: [Tutor] newb help reading lines from csv

2012-10-22 Thread Joel Goldstick
On Mon, Oct 22, 2012 at 3:20 PM, Dewhirst, Rob robdewhi...@gmail.com wrote:
 import csv
 ifile = open('test.csv', r)
 reader = csv.reader(ifile)
 for row in reader:
 print row
 for row in reader:
 print row
 ifile.close()

 This is a simplified version of what I am trying to do - loop through
 a CSV file twice.  Why does the second for loop not execute at all?
 The first one prints the rows of the file just fine.
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

You need to close the file and re open to iterate again.  You can't
reset the iterator back to the beginning without closing and
re-opening

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


Re: [Tutor] newb help reading lines from csv

2012-10-22 Thread Dewhirst, Rob
Thanks Matt and Lazlo.  I knew I must have been missing some counter
not being reset.  Both of those options work fine.

You want to do ifile.seek(0) not reader.seek(0) at least from my testing.


On Mon, Oct 22, 2012 at 2:27 PM, Matt Williams m...@doctors.org.uk wrote:
 Dear Rob,

 This caught me out as well for a long time.

 As I understand it, csv.reader is a file-reader, which iterates ONCE over
 the file. There may be more elegant solutions, but I do:


 import csv
 ifile = open('test.csv', r)
 reader = csv.reader(ifile)
 inData = []
 for row in reader:
 inData.append[row]
 ifile.close()

 you can now loop through inData to your heart's desire.

 HTH,

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


Re: [Tutor] newb help reading lines from csv

2012-10-22 Thread eryksun
On Mon, Oct 22, 2012 at 3:28 PM, LZAntal lzan...@gmail.com wrote:
 On Oct 22, 2012, at 12:20 PM, Dewhirst, Rob robdewhi...@gmail.com wrote:

 import csv
 ifile = open('test.csv', r)
 reader = csv.reader(ifile)

 I believe csv module uses iterator so you need to run reader.seek(0) between 
 the for loops

You have to reset the file iterator with ifile.seek(0). You might also
want a new reader if you care about the line_num attribute, but
otherwise you can keep using the same reader.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Segmentation Fault shenanigans with wx Gui

2012-10-22 Thread Marco Mistroni
Hello Ramit
 yes solution worked...

thanks and regards
 marco

On Mon, Oct 22, 2012 at 5:58 PM, Prasad, Ramit ramit.pra...@jpmorgan.comwrote:

 Marco Mistroni wrote:

  Hello
   i found the problem. It's  calling self.list.ClearAll that causes the
 segmentation fault.
  removing the call to  ClearAll fixed my problem , but i still want to
 clear the list before i  load new
  data..
  could anyone assist?

 I think the problem is the way you populate the data. The issue
 with ClearAll is a side effect of that. See below for more information.

 
  wkr
   marco
  On Fri, Oct 19, 2012 at 11:05 PM, Marco Mistroni mmistr...@gmail.com
 wrote:
  Hi all
   i have written a wx GUI which downloads json data from a server, and
 populate a listbox.
  Every time i populate a listbox, i am receiving Segmentation Faults.
  I have tried to retrieve data from the URL via separate thread, and to
 use events, but i am still getting a
  segmentation fault
 
  could anyone assist pls?
 
  here's relevant code. I m running python on Ubuntu 10.04
 
 [snip]
 
  self.list = AutoWidthListCtrl(panel)'

 This mailing list is for learning Python. Support and familiarity
 with 3rd party packages is limited. You will probably be better off
 asking the wxpython mailing list. Especially as the AutoWidthListCtrl
 is not a widget that comes with wxpython.

 [snip]
 
  def OnResult(self, event):
  print 'onResult'
  ptf_data = event.data
  for item in ptf_data['portfolio']['items']:
  index = self.list.InsertStringItem(sys.maxint, item['ticker'])

 I believe this is the source of your problem. You are using the
 incorrect value as the index. If you look at documentation for
 the base class ListCtrl [0][1] you will notice that the first
 argument to InsertStringItem is the insertion index. Instead you are
 using the same value (sys.maxint) for all items you are inserting.
 sys.maxint represents the maximum integer supported by the system
 and is not relevant for what you are trying to do. Instead use an
 incrementing count.

  rows = self.list.GetItemCount()
  for index, item in enumerate( ptf_data['portfolio']['items'], rows ):
  self.list.InsertStringItem(index, item['ticker'])

  [0]: http://wiki.wxpython.org/ListControls
 [1]: http://www.wxpython.org/docs/api/wx.ListCtrl-class.html

  self.list.SetStringItem(index, 1, item['name'])
  self.list.SetStringItem(index, 2, str(item['movingAvg200']))
  self.list.SetStringItem(index, 3, str(item['movingAvg50']))
  self.list.SetStringItem(index, 4, str(item['price']))
  self.list.SetStringItem(index, 5, str(item['previous']))
  self.list.SetStringItem(index, 6, str(item['price'] -
 item['previous']) )
  self.list.SetStringItem(index, 7, str(item['totalValue']))
  self.list.SetStringItem(index, 8, str(item['position']))
 

 Do let us know if the suggestion works or not.

 Ramit Prasad


 This email is confidential and subject to important disclaimers and
 conditions including on offers for the purchase or sale of
 securities, accuracy and completeness of information, viruses,
 confidentiality, legal privilege, and legal entity disclaimers,
 available at http://www.jpmorgan.com/pages/disclosures/email.
 ___
 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] newb help reading lines from csv

2012-10-22 Thread Joel Goldstick
On Mon, Oct 22, 2012 at 3:35 PM, Dewhirst, Rob robdewhi...@gmail.com wrote:
 Thanks Matt and Lazlo.  I knew I must have been missing some counter
 not being reset.  Both of those options work fine.

 You want to do ifile.seek(0) not reader.seek(0) at least from my testing.


 On Mon, Oct 22, 2012 at 2:27 PM, Matt Williams m...@doctors.org.uk wrote:
 Dear Rob,

 This caught me out as well for a long time.

 As I understand it, csv.reader is a file-reader, which iterates ONCE over
 the file. There may be more elegant solutions, but I do:


 import csv
 ifile = open('test.csv', r)
 reader = csv.reader(ifile)
 inData = []
 for row in reader:
 inData.append[row]
 ifile.close()

 you can now loop through inData to your heart's desire.

 HTH,

 Matt


If you want to learn more about python iterators this is a good place
to start: http://docs.python.org/howto/functional.html#iterators
or google python iterators.  They are pretty cool to understand
-- 
Joel Goldstick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] newb help reading lines from csv

2012-10-22 Thread eryksun
On Mon, Oct 22, 2012 at 3:35 PM, Dewhirst, Rob robdewhi...@gmail.com wrote:

 import csv
 ifile = open('test.csv', r)
 reader = csv.reader(ifile)
 inData = []
 for row in reader:
 inData.append[row]
 ifile.close()

 you can now loop through inData to your heart's desire.

Alternatively:

import csv
with open('test.csv', 'rb') as ifile:
inData = list(csv.reader(ifile))
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Help - Using Sort and Join

2012-10-22 Thread Daniel Gulko

Hi Python Tutor,

I have an issue trying to figure out how to print out final answers using sort 
and join functions.

Assignment Specification:
make a function that is a magic eight ball emulator. emulator will be a 
function that returns one of the possible answers. Make another function that 
runs the emulator over and over again until user wants to quit, printing answer 
each time. When user quits, present all answers that the user got again, but 
present them in alphabetical order. Use the join() function available for 
strings for this.

Below is an example output from my code:

ask a question (or press 'enter' to quit): will I be rich
You may rely on it.

ask a question (or press 'enter' to quit): will I be poor
It is decidedly so.

ask a question (or press 'enter' to quit): why is that
Better not tell you now.

As my code is written when user presses enter I simply break and print this 
current output:
Have a nice day


What I want is when user exits for my code to take all previous answers, 
joining them and sorting them like below:
ask a question (or press 'enter' to quit):
You may rely on it. It is decidedly so. Better not tell you now.

My code works right now but I am missing the final part in how to join and sort 
all answers. Any suggestions or examples is helpful as I 
am very new with Python.

Current code is attached for viewing.

Thanks,

Dan

  import random

def AskMagicEightBall():

answers = (As I see it, yes., 
   It is certain., 
   It is decidedly so., 
   Most likely., 
   Outlook good., 
   Signs point to yes., 
   Without a doubt., 
   Yes., 
   Yes – definitely., 
   You may rely on it.,
   Reply hazy, try again., 
   Ask again later., 
   Better not tell you now., 
   Do not count on it., 
   My reply is no., 
   My sources say no., 
   Outlook not so good., 
   Very doubtful.)

return random.choice(answers)

def RunEmulator():

while True:
question = raw_input(ask a question (or press 'enter' to quit): )
if question:
answers=AskMagicEightBall()
print answers
elif not question:
print Have a nice day
break

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


Re: [Tutor] Help - Using Sort and Join

2012-10-22 Thread Dave Angel
On 10/22/2012 03:57 PM, Daniel Gulko wrote:
 Hi Python Tutor,

 I have an issue trying to figure out how to print out final answers using 
 sort and join functions.

 Assignment Specification:
 make a function that is a magic eight ball emulator. emulator will be a 
 function that returns one of the possible answers. Make another function that 
 runs the emulator over and over again until user wants to quit, printing 
 answer each time. When user quits, present all answers that the user got 
 again, but present them in alphabetical order. Use the join() function 
 available for strings for this.

 Below is an example output from my code:

 ask a question (or press 'enter' to quit): will I be rich
 You may rely on it.

 ask a question (or press 'enter' to quit): will I be poor
 It is decidedly so.

 ask a question (or press 'enter' to quit): why is that
 Better not tell you now.

 As my code is written when user presses enter I simply break and print this 
 current output:
 Have a nice day


 What I want is when user exits for my code to take all previous answers, 
 joining them and sorting them like below:
 ask a question (or press 'enter' to quit):
 You may rely on it. It is decidedly so. Better not tell you now.

 My code works right now but I am missing the final part in how to join and 
 sort all answers. Any suggestions or examples is helpful as I 
 am very new with Python.

 Current code is attached for viewing.

 Thanks,

 Dan


You should assume that people cannot get an attachment.  Some can and
some cannot.  Just put the code inline, and make sure you're writing a
text message.  (Your current one is html, another flaw that can cause
some to not get it the way you sent it)

Anyway, if you want to present a summary at the end, you'll have to
build a list as you go.  At the beginning of your function, create an
empty list.  Then append to it each message you're outputting.  Then
when you fall out of the loop, you can manipulate that list as your
assignment says, first sorting it, then using join to create a single
string from the list.

Also, you don't need an elif, since you already know the condition there
will be true.  Just use if and else, and just use a break under else. 
Then outside the loop, you can do as much as you like to give the final
information.





-- 

DaveA

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


Re: [Tutor] Help - Using Sort and Join

2012-10-22 Thread Oscar Benjamin
On 22 October 2012 20:57, Daniel Gulko dangu...@hotmail.com wrote:
 Hi Python Tutor,

Hi Daniel,

 I have an issue trying to figure out how to print out final answers using
 sort and join functions.

Do you know how to use sort and join to print a list of strings in
alphabetical order?


 Assignment Specification:
 make a function that is a magic eight ball emulator. emulator will be a
 function that returns one of the possible answers. Make another function
 that runs the emulator over and over again until user wants to quit,
 printing answer each time. When user quits, present all answers that the
 user got again, but present them in alphabetical order. Use the join()
 function available for strings for this.

 As my code is written when user presses enter I simply break and print this
 current output:
 Have a nice day

 What I want is when user exits for my code to take all previous answers,
 joining them and sorting them like below:
 ask a question (or press 'enter' to quit):
 You may rely on it. It is decidedly so. Better not tell you now.

The problem is that your not saving the answers so at the point where
your program ends they aren't available for you to print them. You
should use a list to collect the answers as they are generated. Then
you can think about how to use the sort and join functions


 My code works right now but I am missing the final part in how to join and
 sort all answers. Any suggestions or examples is helpful as I
 am very new with Python.

 Current code is attached for viewing.

Your code is not too long to be pasted directly into the email:

'''
import random

def AskMagicEightBall():

answers = (As I see it, yes.,
   It is certain.,
   It is decidedly so.,
   Most likely.,
   Outlook good.,
   Signs point to yes.,
   Without a doubt.,
   Yes.,
   Yes – definitely.,
   You may rely on it.,
   Reply hazy, try again.,
   Ask again later.,
   Better not tell you now.,
   Do not count on it.,
   My reply is no.,
   My sources say no.,
   Outlook not so good.,
   Very doubtful.)

return random.choice(answers)

def RunEmulator():

while True:
question = raw_input(ask a question (or press 'enter' to quit): )
if question:
answers=AskMagicEightBall()
print answers
elif not question:
print Have a nice day
break

RunEmulator()
'''


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


Re: [Tutor] newb help reading lines from csv

2012-10-22 Thread Prasad, Ramit
Dewhirst, Rob wrote: 
 Thanks Matt and Lazlo.  I knew I must have been missing some counter
 not being reset.  Both of those options work fine.
 
 You want to do ifile.seek(0) not reader.seek(0) at least from my testing.
 
 
 On Mon, Oct 22, 2012 at 2:27 PM, Matt Williams m...@doctors.org.uk wrote:
[snip]

Please do not top post. This list's etiquette is to write your 
response in-line or below the quoted text. Thank you.

Ramit Prasad

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Which is better Practice and why

2012-10-22 Thread Steven D'Aprano

On 22/10/12 22:45, Matthew Ngaha wrote:

In many of the tutorial examples ive come across, the main code's program
is never at the top level, but always in a function of some sort. i
understand why but, there is always a different way used to access the main
code, i want to know which is the best.


main()
  main's code

#top level
main()



Not that. That unconditionally executes main the first time you access
the module, *regardless* of whether it is being run as a script or
being imported. That is nearly always the wrong thing to do.

It's particularly awful because importing the module for a second time
will not re-run the main program. You have to exit Python, restart it,
and then re-import the module again.




they call the main program by simply calling the main function. I've also
seen a more complcated:

if __name__ == '__main__':
 main()



This one is best. It only runs the main function when the module is being
run as a script.



the 2nd one usually includes a lot more code then i showed.


Yes, that's because when people write proper scripts, they tend to write
code for handling errors, checking the command line arguments, etc. When
people just slap together a lazy always execute the main function, they
tend to not bother.

Or perhaps that's just how I work :)


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


[Tutor] Iterators, example (need help)

2012-10-22 Thread Bryan A. Zimmer
Hello, all.


I am a long-time programmer with little experience in Python, but am
trying to learn. The example program, attached, is a toy app with a
GUI that merely prints out environment keys and their associated
values.

I know there are errors in the program, but I wanted to see if someone
can tell me something about the iterator magic that this program is
trying to use.

The whole program was designed on, and written for cygwin (bash shell)
under Windows 7. The python version is 2.6.3. I haven't tried it on
other platforms but it should work under Windows and Linux.

I want to understand what I stumbled into here in order to develop the
code and use similar techniques in the future. Specifically, is it
really necessary to use __iter__ and __next__ as system functions
(with the double underscores)? I can program the basic program in any
number of ways but was enthralled by the concept of iterators and
generators.

I know I missed the mark while trying to use the pythonic idiom, but maybe
you can help me see where I went astray.

Hopefully you will forgive my home-grown oop and GUI skills, I am from
the old school of programming, prior to when these became necessities.

The original inspiration for the code came from Dive Into Python,
from the section about iterators and classes, from the fibonacci2.py
example.

Thank you

Bryan A. Zimmer


from Tkinter import *
import os

ignore1='''

This program works to do what I set out to do as a first step
BAZ 10/19/2012

'''


class Env:
''' This class represents the environment of the current process'''
def __init__(self, master=None):
self.d = os.environ.keys()
self.v = os.environ.values()
self.i = 0
self.y = self.v[self.i]
self.x = self.d[self.i]


def __iter__(self):
self.x = self.d[self.i]
self.y = self.v[self.i]
return self



def __next__(self,master=None):
global s1
global s2

self.i += 1 
if (self.i  len(self.d)):
self.x = self.d[self.i]
self.y = self.v[self.i]

if (self.x):
print self.x, '==', self.y
s1.set(self.x)
s2.set(self.y)
else:
print (raising Stop Iteration)
raise StopIteration
return ((self.x, self.y))


class App(object):
''' This is the main GUI app'''
def __init__(self,master):
self.createWidgets()

def createWidgets(self,master=None):
global s1
global s2
self.fm1 = Frame(master)
self.fm2 = Frame(master)
self.fm1.pack(side = TOP, anchor=NW, fill=BOTH,expand=YES)
self.fm2.pack(side = TOP, anchor=SW, fill=BOTH,expand=YES)
 
s1=StringVar()
s1.set(env.x)
self.l1=Label(self.fm1,text='Var:')
self.l1.pack(side=LEFT,fill=X,expand=NO,padx=10)  
e1=Entry(self.fm1,textvariable=s1,width=40)
e1.pack(side=LEFT,fill=X,expand=YES,padx=10)
 
self.l2=Label(self.fm2,text='Val: ')
self.l2.pack(side=LEFT,fill=X,expand=NO,padx=10) 
s2=StringVar()
s2.set(env.y)

e2=Entry(self.fm2,textvariable=s2, width=40)
e2.pack(side=LEFT,fill=X,expand=YES,padx=9)
   
self.b1=Button(self.fm2,text='Next',command=env.__next__)
self.b1.pack(side=TOP,anchor=S,fill=X,expand=YES,padx=10)


if __name__=='__main__':
env=Env()
root = Tk()
root.option_add('*font', ('verdana', 12, 'bold'))
root.title(Pack - Example 12)
app=App(root)
root.mainloop()

---

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


Re: [Tutor] Iterators, example (need help)

2012-10-22 Thread Prasad, Ramit
Bryan A. Zimmer wrote:
 Hello, all.
 
 
 I am a long-time programmer with little experience in Python, but am
 trying to learn. The example program, attached, is a toy app with a
 GUI that merely prints out environment keys and their associated
 values.
 
 I know there are errors in the program, but I wanted to see if someone
 can tell me something about the iterator magic that this program is
 trying to use.
 
 The whole program was designed on, and written for cygwin (bash shell)
 under Windows 7. The python version is 2.6.3. I haven't tried it on
 other platforms but it should work under Windows and Linux.
 
 I want to understand what I stumbled into here in order to develop the
 code and use similar techniques in the future. Specifically, is it
 really necessary to use __iter__ and __next__ as system functions
 (with the double underscores)? I can program the basic program in any
 number of ways but was enthralled by the concept of iterators and
 generators.

Typically you call iter(obj)  and next(iter_object) when you need to
call them and not .__iter__() or .__next__(). This applies to many
built-in commands like len(obj).

 
 I know I missed the mark while trying to use the pythonic idiom, but maybe
 you can help me see where I went astray.
 
 Hopefully you will forgive my home-grown oop and GUI skills, I am from
 the old school of programming, prior to when these became necessities.

Practice (and constructive criticiscm) makes perfect. Also note,
I am unfamiliar with Tkinter and am basing some comments off experience
with wxpython. Some things will be different but principles should
be fairly similar.

 
 The original inspiration for the code came from Dive Into Python,
 from the section about iterators and classes, from the fibonacci2.py
 example.
 
 Thank you
 
 Bryan A. Zimmer
 
 
 from Tkinter import *

This is a frowned upon import style as it can easily override existing
names. Instead use:

import Tkinter as tk # You can change tk to something else.
# And then access everything in Tkinter as...
self.fm1 = tk.Frame() # use tk or whatever you imported Tkinter as.

 import os
 
 ignore1='''
 
 This program works to do what I set out to do as a first step
 BAZ 10/19/2012
 
 '''
 
 
 class Env:
 ''' This class represents the environment of the current process'''
 def __init__(self, master=None):
 self.d = os.environ.keys()
 self.v = os.environ.values()
 self.i = 0
 self.y = self.v[self.i]
 self.x = self.d[self.i]

Why are you storing these values? They will not update
in realtime. Of course, environment variables may not
change so this might not matter.

 
 
 def __iter__(self):
 self.x = self.d[self.i]
 self.y = self.v[self.i]
 return self

Environment variables do not seem like something that really
needs to be iterable. Although, if I was going to do that
I would instead just store os.environ dictionary (instead
of keys and values) and iterate over that.

Also, if you are going to return self, you need to change
`def __next__` to `def next`. At least, that is true for
Python 2, but it may not be true in Python 3.

 e = Env()
 ie = iter(e)
 next(ie)
TypeError: instance has no next() method
 for o in ie:
... print o
... 
TypeError: instance has no next() method

 for o in e:
... print o
... 
TypeError: instance has no next() method

 
 
 
 def __next__(self,master=None):
 global s1
 global s2
 
 self.i += 1

This incrementing of i should probably done at the end of the 
loop, because otherwise you always lose what is stored in self.d[0] /self.v[0]. 
Or you can set self.i to -1 initially.

 if (self.i  len(self.d)):
 self.x = self.d[self.i]
 self.y = self.v[self.i]
 
 if (self.x):
 print self.x, '==', self.y
 s1.set(self.x)
 s2.set(self.y)

What are s1 and s2? Why should they be global? Why not return 
here directly? What happens if the key is None?

 else:
 print (raising Stop Iteration)
 raise StopIteration
 return ((self.x, self.y))
 

It seems like you are replicating the functionality for dict.items().
I suppose this is mostly a learning exercise so that is fine, otherwise 
I would just use a dictionary instead.

 
 class App(object):
 ''' This is the main GUI app'''
 def __init__(self,master):
 self.createWidgets()
 
 def createWidgets(self,master=None):
 global s1
 global s2
 self.fm1 = Frame(master)
 self.fm2 = Frame(master)
 self.fm1.pack(side = TOP, anchor=NW, fill=BOTH,expand=YES)
 self.fm2.pack(side = TOP, anchor=SW, fill=BOTH,expand=YES)

s1 and s2 should be passed in and not be a global variable.
If you need to update the data later, then create an update
method instead of looking at global variables. 

 
 

Re: [Tutor] Iterators, example (need help)

2012-10-22 Thread Alan Gauld

On 23/10/12 00:32, Prasad, Ramit wrote:

Most of Ramit's comments are valid, this is just a couple of additional
notes.


from Tkinter import *


This is a frowned upon import style as it can easily override existing
names. Instead use:

import Tkinter as tk # You can change tk to something else.


import * is common for Tkinter apps, but its still better in production 
code to use the '...as tk' style.



import os

ignore1='''

This program works to do what I set out to do as a first step
BAZ 10/19/2012

'''


You don't need the ignore= bit.

Just make it a doc string in the code.


class Env:
 ''' This class represents the environment of the current process'''
 def __init__(self, master=None):
 self.d = os.environ.keys()
 self.v = os.environ.values()
 self.i = 0
 self.y = self.v[self.i]
 self.x = self.d[self.i]



 def __iter__(self):
 self.x = self.d[self.i]
 self.y = self.v[self.i]
 return self


Environment variables do not seem like something that really
needs to be iterable. Although, if I was going to do that
I would instead just store os.environ dictionary (instead
of keys and values) and iterate over that.


Agreed, I'd rather store the dict directly in the class.


What are s1 and s2? Why should they be global? Why not return
here directly? What happens if the key is None?


They are defined in the later code, but I agree they don't
need to be global. Accessing values across classes is bad
practice. It would be better that if you really want
s1,s2 to be global that you define them in global scope
outside any of the class definitions. It makes them easier
to find!


 else:
 print (raising Stop Iteration)

  raise StopIteration

I assume its only for debugging but printing a message and raising an 
exception should not be done. Its for the exception handling code to 
decide if a message is needed.




class App(object):
 ''' This is the main GUI app'''
 def __init__(self,master):
 self.createWidgets()

 def createWidgets(self,master=None):
 global s1
 global s2
 self.fm1 = Frame(master)
 self.fm2 = Frame(master)
 self.fm1.pack(side = TOP, anchor=NW, fill=BOTH,expand=YES)
 self.fm2.pack(side = TOP, anchor=SW, fill=BOTH,expand=YES)


s1 and s2 should be passed in and not be a global variable.
If you need to update the data later, then create an update
method instead of looking at global variables.



 s1=StringVar()
 s1.set(env.x)


env is not set in the code and so I have no idea what this refers to.


It's in the main() function but not declared as global here which is 
inconsistent and confusing. Again better to put it into the class.



I suppose by the time this gets created there is an env in the global
scope, but I think this is chancy and will only work from this script.
You cannot reuse or import class App from another program.
Instead pass env into the __init__ method.

I have not run this program, but I am pretty sure this button will
not update e1 and e2. Not to mention that you need to store e1/e2
somewhere you can access later.


This is a bit of Tkinter magic that means the entries are auto updated 
when the variable values change (and vice versa). That's what a 
StringVar does. So I think you are Ok here.


HTH,

--
Alan G
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] Which is better Practice and why

2012-10-22 Thread Devin Jeanpierre
On Mon, Oct 22, 2012 at 6:15 PM, Steven D'Aprano st...@pearwood.info wrote:
 Not that. That unconditionally executes main the first time you access
 the module, *regardless* of whether it is being run as a script or
 being imported. That is nearly always the wrong thing to do.

Recently I've become a fan of executable packages. In __main__.py,
it's always the right thing to do.

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


Re: [Tutor] Which is better Practice and why

2012-10-22 Thread Devin Jeanpierre
On Mon, Oct 22, 2012 at 9:23 AM, Walter Prins wpr...@gmail.com wrote:
 Devin,

 On 22 October 2012 12:54, Devin Jeanpierre jeanpierr...@gmail.com wrote:
 On Mon, Oct 22, 2012 at 7:45 AM, Matthew Ngaha chigga...@gmail.com wrote:
 the 2nd one usually includes a lot more code then i showed. can you please
 tell me why different methods are used to access the main code? is it just
 preference or is one way actually better coding practice?

 The second one is used if your importable modules are also scripts
 that can be executed.

 That's a bad idea, because it results in the same source file being
 executed twice, producing distinct classes that break typechecking. If
 you have myprogram.py containing the following source code, and
 execute it as a program, it will terminate with an uncaught MyError.

 class MyError(Exception): pass

 import myprogram
 try: raise myprogram.MyError
 except MyError: pass

 Why would you do this though?  Is the source of the problem not really
 that you're importing a module inside itself?  Why would you generally
 want to do this? Furthermore the 'if __name__ == __main__' idiom is
 explicitly part of Python and generally well accepted (so it seems to
 me at least), so the above seems like a fairly esoteric objection to
 its use?

It's that your module was imported, while it was executed as a script.

It's fairly common for modules to import each other for various
reasons. Especially if one module is executable, it might do
circular imports for the purposes of its execution (tests or what
have you), and these break because the reverse part of the circle
actually create a new module rather than doing a circular import.

This kind of behavior is pretty much impossible if your scripts are
scripts, and your modules are modules. The only downside is that you
have to import the code you use in your scripts.

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


Re: [Tutor] Which is better Practice and why

2012-10-22 Thread Steven D'Aprano

On 22/10/12 22:54, Devin Jeanpierre wrote:

On Mon, Oct 22, 2012 at 7:45 AM, Matthew Ngahachigga...@gmail.com  wrote:

the 2nd one usually includes a lot more code then i showed. can you please
tell me why different methods are used to access the main code? is it just
preference or is one way actually better coding practice?


The second one is used if your importable modules are also scripts
that can be executed.

That's a bad idea,


I disagree. See below.



because it results in the same source file being executed twice,


Not so. That only happens if your module is executed *and* imported
simultaneously. It is perfectly safe to write a module which can be run
as a script, or imported, so long as you don't do both at the same time
from within a single Python process.

Excluding test scripts, I find 145 modules in the Python 2.5 standard
library, and 127 in the Python 3.3 std lib, that use the if __name__ ==
idiom to be both importable and runnable as a script.



producing distinct classes that break typechecking. If
you have myprogram.py containing the following source code, and
execute it as a program, it will terminate with an uncaught MyError.

 class MyError(Exception): pass

 import myprogram
 try: raise myprogram.MyError
 except MyError: pass


Then don't do that.

There are very few reasons for importing a module from within itself, and
those reasons are relatively advanced, e.g.:

- circular imports
- some types of introspection

If you do that, and the module directly or indirectly imports itself
while it is running as a script, you may run into trouble. But writing
a dual-purpose module that is usable as an importable module or as a
stand-alone script is not problematic in itself.




So, in any circumstance where you would use the second one, it's
because you're in a situation where bad things are happening.


The bad situation is when you have circular imports, including the
case where your module imports itself.



So use the first one always.


This is contrary to the advice given in the Fine Manual:

http://docs.python.org/library/__main__.html


More from Python's creator, GvR, and the Effbot:

http://www.artima.com/forums/flat.jsp?forum=106thread=4829

http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm




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


Re: [Tutor] Iterators, example (need help)

2012-10-22 Thread Steven D'Aprano

On 23/10/12 09:30, Bryan A. Zimmer wrote:


I know there are errors in the program, but I wanted to see if someone
can tell me something about the iterator magic that this program is
trying to use.


In simple terms: an iterator is a sequence of items that understands
the iterator protocol. If you say to it, iterator, please give me
the next value, it will respond by giving you the next value in the
sequence.

Of course you don't literally talk to it, you use an object-oriented
method call. Or more frequently, you simply define the appropriate
magic methods and let Python handle the rest.

There's nothing that you can do with iterators that can't be done some
other way, but they are a great way to process sequences of data
without needing to accumulate the data up front, such as in a list.
For example, it is trivially easy to produce an iterator that returns
a never-ending stream of data.

Nearly all magic methods in Python have double leading and trailing
underscores. There are lots of them, but 99.9% of the time you don't
explicitly use them *except* to define them in your class. Then you
either iterate over the object:

for item in some_iterator:
...


or occasionally pull out a single item:

item = next(some_iterator)



Iterators have two dunder (Double UNDERscore) magic methods:

__next__
__iter__


In general, your __iter__ method will be trivially simple:

def __iter__(self):
return self

and most of the logic will be in __next__. I see your __iter__
method is a little more complicated, but I haven't studied it
in detail to see if the extra complication is justified.




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


Re: [Tutor] Creating a list from other lists

2012-10-22 Thread Steven D'Aprano

On 22/10/12 21:52, eryksun wrote:

On Mon, Oct 22, 2012 at 6:37 AM, Steven D'Apranost...@pearwood.info  wrote:

On 22/10/12 21:21, Saad Javed wrote:


for x, y , z in zip(a, b, c):
L.extend([x, y, z])
print L


This is not your code, because that gives a SyntaxError. Where is
the indentation? Indentation is required in Python, if you leave it
out, your code will not work correctly.


It's an HTML post.



Not according to the version of Thunderbird I am using, which shows it
as a plain text email.

I suspect that the HTML attachment may be invalid HTML, understandable
by Gmail and possibly nothing else. Typical of Google :(



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


Re: [Tutor] Iterators, example (need help)

2012-10-22 Thread Oscar Benjamin
On 23 October 2012 01:43, Steven D'Aprano st...@pearwood.info wrote:
 In general, your __iter__ method will be trivially simple:

 def __iter__(self):
 return self

 and most of the logic will be in __next__. I see your __iter__
 method is a little more complicated, but I haven't studied it
 in detail to see if the extra complication is justified.

The __iter__ method performs the same operation that is already
performed in __init__ and __next__ so it is redundant. Probably it
should reset the counter to restart iteration. However, in the
provided code it is never called since the Env instance is never used
in a for loop or iter() call.


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


Re: [Tutor] Which is better Practice and why

2012-10-22 Thread Devin Jeanpierre
On Mon, Oct 22, 2012 at 8:42 PM, Steven D'Aprano st...@pearwood.info wrote:
 If you do that, and the module directly or indirectly imports itself
 while it is running as a script, you may run into trouble. But writing
 a dual-purpose module that is usable as an importable module or as a
 stand-alone script is not problematic in itself.

Yes. However, it is somewhat hard to guarantee that a module won't
indirectly import itself for a large codebase. It certainly sometimes
happens by accident.

 So use the first one always.
 This is contrary to the advice given in the Fine Manual:

 http://docs.python.org/library/__main__.html


 More from Python's creator, GvR, and the Effbot:

 http://www.artima.com/forums/flat.jsp?forum=106thread=4829

 http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm

It's very easy for me to overstate my case. Maybe I even have already,
just because I wasn't taking very long to explain myself.

I have concrete reasons to not use this form. It comes up very rarely,
and is not a large issue. Heck, it's not even really worth making a
big fuss over. But there is the occasional mess-up where it happens.

I am also aware that what I prefer goes against idiom. But to me, this
minor concrete use-case beats out idiom. After all, what is the
benefit to following this particular idiom? I believe the answer is,
you get to use one .py file instead of two -- and as I see it, the
cases where circular imports might be a problem are precisely those
where you don't care too much about the number of files, because
you're writing a package anyway.

As it happens, I sort of stumbled across this worldview when I was
forced into separating modules from scripts with the new __main__
submodule system to make executable packages (So it's even possible
for Pythonic code to forgo the name check). It really struck something
in me, and I had a (subjective) realization that modules and scripts
are fundamentally different, and that there's very little benefit to
conflating them. I realize this isn't really a view that's mainstream
for Python. Also, I realize it's not a particularly interesting
realization -- any C# programmer would tell you this. And presumably,
Pythonistas as a group would disagree.

(As an aside, I find it interesting how much more beautiful GvR's code
in that post becomes if you consider turning the common bits into a
@main decorator).

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


Re: [Tutor] Which is better Practice and why

2012-10-22 Thread Steven D'Aprano

On 23/10/12 11:25, Devin Jeanpierre wrote:

On Mon, Oct 22, 2012 at 6:15 PM, Steven D'Apranost...@pearwood.info  wrote:

Not that. That unconditionally executes main the first time you access
the module, *regardless* of whether it is being run as a script or
being imported. That is nearly always the wrong thing to do.


Recently I've become a fan of executable packages. In __main__.py,
it's always the right thing to do.


I would disagree there too. I think that unconditionally running main
is the wrong thing to do, except perhaps in the most trivial quick-and-
dirty scripts. But if the script it that trivial, you might not even
bother with a main function at all.

package.__main__.py is designed to be run as a script, and not to be
imported. But that doesn't mean that there's no good purpose for
importing it. If your package is non-trivial, you ought to have tests
for it, including package.__main__. Those tests will probably want to
import the module, not necessarily run it as a script.


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


Re: [Tutor] Which is better Practice and why

2012-10-22 Thread Devin Jeanpierre
On Mon, Oct 22, 2012 at 8:54 PM, Steven D'Aprano st...@pearwood.info wrote:
 Recently I've become a fan of executable packages. In __main__.py,
 it's always the right thing to do.


 I would disagree there too. I think that unconditionally running main
 is the wrong thing to do, except perhaps in the most trivial quick-and-
 dirty scripts. But if the script it that trivial, you might not even
 bother with a main function at all.

 package.__main__.py is designed to be run as a script, and not to be
 imported. But that doesn't mean that there's no good purpose for
 importing it. If your package is non-trivial, you ought to have tests
 for it, including package.__main__. Those tests will probably want to
 import the module, not necessarily run it as a script.

I think you will find that it is never the case that __name__ !=
'__main__' in a file called __main__.py.

If I want to test something, I put it in another file. My __main__.py
file will generally look something like this:

from . import game
game.Game().run()

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