RE: List loops

2007-10-09 Thread Hamilton, William
> From: Tommy Grav
> 
> Hi everyone,
> 
>I have a list of objects where I have want to do two loops.
> I want to loop over the list and inside this loop, work on all
> the elements of the list after the one being handled in the outer
> loop. I can of course do this with indexes:
> 
>  >>> alist = range(3)
>  >>> for i in xrange(len(alist)):
> ...   for j in xrange(i+1,len(alist)):
> ... print i,j,alist[i],alist[j]
> ...
> 0 1 0 1
> 0 2 0 2
> 1 2 1 2
>  >>>
> 
> 
> Is there a way to do this without using indexes?
> 

You have to use indices because you are printing the indices.  Given
that, the following loop does what it looks like you are trying to do.

>>> alist = range(3)
>>> for index, i in enumerate(alist):
for jndex, j in enumerate(alist[index:]):
print index, jndex, i, j


0 0 0 0
0 1 0 1
0 2 0 2
1 0 1 1
1 1 1 2
2 0 2 2
>>>


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


RE: tkinter question

2007-10-08 Thread Hamilton, William
> -Original Message-
> From: Kevin Walzer
> 
> See
http://www.codebykevin.com/blosxom/business/phynchronicity-new.png:
> this is an application I develop. The layout is all handled by "pack"
> and paned windows. Where you you use "grid" in a layout like this?
> 

I'd use a three row grid, with the middle row containing a frame with
another grid in it.  I don't try to create a single massive grid that
manages everything, I break it up into subgrids of related widgets.

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


RE: sorteddict [was a PEP proposal, but isn't anymore!]

2007-10-01 Thread Hamilton, William
> From: thebjorn
> What's stabledict? I'm assuming that ordereddict is a mapping that
> maintains insertion order(?)

Yes, ordereddict is a dict that maintains insertion order.  Stabledict
is probably a dict that maintains _an_ order, so that repr() and the
like return the same value when used on dicts containing the same data.

> In the Smalltalk collection hierarchy SortedCollection is a subclass
> of OrderedCollection, which implies to me that it'd be better to add
> an ordereddict first.

That depends entirely on how ordereddict and sorteddict function.  If
they are similar there might be a benefit.  However, an ordereddict
would probably be best implemented with an internal list of keys,
whereas the consensus seems to be using a tree for sorteddict.  In this
case, trying to build sorteddict from ordereddict is going to give you
extra baggage and overhead for no benefit.


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


RE: sorteddict PEP proposal [started off as orderedict]

2007-09-25 Thread Hamilton, William
> From: Paul Hankin
> 
> 
> Here's a first go. Sorting occurs when the keys are iterated over,
> making it fast (almost as a dict) for construction, insertion, and
> deletion, but slow if you're iterating a lot. You should look at some
> use cases to decide if this approach is best, or if a sorted
> datastructure should be used instead, but my instinct is that this is
> a decent approach. Certainly, you're unlikely to get a simpler
> implementation :)
> 
> class sorteddict(dict):
> "A sorted dictionary"
> def __init__(self, arg=None, cmp=None, key=None, reverse=False):
> if arg:
> super(sorteddict, self).__init__(arg)
> else:
> super(sorteddict, self).__init__()
> self._cmp = cmp
> self._key = key
> self._reverse = reverse
> def keys(self):
> return sorted(super(sorteddict, self).keys(), cmp=self._cmp,
> key=self._key, reverse=self._reverse)
> def iter_keys(self):
> return (s for s in self.keys())
> def items(self):
> return [(key, self[key]) for key in self.keys()]
> def iter_items(self):
> return ((key, self[key]) for key in self.keys())
> def values(self):
> return [self[key] for key in self.keys()]
> def iter_values(self):
> return (self[key] for key in self.keys())
> def __str__(self):
> return '{' + ', '.join('%s: %s' % (repr(k), repr(v))
> for k, v in self.iter_items()) + '}'
> def __repr__(self):
> return str(self)
> def __iter__(self):
> return self.iter_keys()


You could speed up keys() at the cost of memory if you maintained a list
of keys in the instance.  Doing so would let you use an "unsorted" flag
that gets set when a new key is added and checked when keys() is called.
If the flag is unset, just return a copy of the list.  Otherwise, sort
the list in place, return a copy, and unset the flag.  (Copies because
you don't want the master key list to be modified by code using the
class.)

The use case for this seems to be when you have a dictionary that you
need to often work through in sorted order.  Sorting the keys every time
keys() is called isn't an improvement over using a regular dict and
sorting the keys normally.  So the extra memory cost of maintaining an
internal keys list looks reasonable to me.



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


RE: An ordered dictionary for the Python library?

2007-09-12 Thread Hamilton, William
> From: Michele Simionato
> 
> On Sep 12, 3:54 pm, Mark Summerfield <[EMAIL PROTECTED]>
> wrote:
> > On 12 Sep, 13:46, Michele Simionato <[EMAIL PROTECTED]>
> >
> > Actually I meant by key order, so insertion order doesn't matter at
> > all. If you need a dictionary-like data structure that respects
> > insertion order you could use a list of (key, value) tuples.
> >
> > Another respondent asked about use cases.
> >
> > I have found time and again that I needed (key, value) pairs where
the
> > key is some string that provides a representation for human readers
> > and the value is some internal key (e.g., database ID) that the
system
> > uses internally. In these cases I often need to present the user
with
> > a list of items from which to choose and want to present them in
> > sorted order. Naturally, I could use an ordinary dict and then do
> > this:
> >
> > for string in sorted(d.keys()):
> > process(string)
> >
> > But what happens when I need to do this a *lot* and when the number
of
> > items is hundreds or a few thousands? I'm having to sort again and
> > again, since it is often the case that the items in the list changes
> > during the runtime of the application. So my solution in C++ is to
use
> > an ordered dictionary (a map in C++ jargon), which in Python means I
> > can simply write:
> >
> > for string in od.keys():
> > process(string)
> >
> 
> For your use case I would wrap a list [(key, value)] with a dict-like
> object and I would use the bisect module in the standard library to
> keep
> the inner list ordered.


Or subclass dict to carry along a sorted list of keys with it and return
that when dict.keys() is called.  Even better, only have .keys() sort
the keys list when a key has been added to it since the last call.


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


RE: Python code-writing for the blind. Was (Re: newbie: stani's pythoneditor if-else)

2007-09-11 Thread Hamilton, William
> From: madzientist
> 
> Thanks, everybody, for the very very useful and kind responses.
> 
> There is a second reason why I asked the question about automatic de-
> indenting. I am teaching myself Python partly so I can then help my
> technically astute, but blind friend learn programming. For the many
> reasons that Pythonistas like to cite often, I thought Python would be
> a good choice to learn programming, and that perhaps the indentation
> problem would be solved by the use of an intelligent editor.
> 
> But now I am not so sure, though I will try Emacs. Is there anyone
> here with experience in such issues ? Maybe for her sake, I should
> switch to learning Perl ;) ;)
> 
> More seriously, the added issue is that SPE uses spaces, not a single
> tab to indent the lines, and I believe it is extremely tedious to use
> screen-readers to keep track of blank spaces at the beginning of each
> line. I have not tried it myself yet, but I will soon.
> 
> Is Python a bad choice for the blind programmer, as a result of a
> tight linkage between visual aspects of the code and its function ? I
> wish the site blindprogramming.com weren't so lifeless...
> 

Can you set SPE to use a single space rather than the typical four
spaces?  Python should accept it just fine.  You'll still have problems
reading other people's code.  Maybe you can write a quick script that
converts code down to one-space indents.


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


RE: Excel process still running after program completion.

2007-09-11 Thread Hamilton, William
> From: Chris
>
> I have a python script that is driving Excel and using the win32com
> module. However, upon program completion there's still an Excel.exe
> process running in the background that I must terminate through Task
> Manager. Reading up on other threads indicate that maybe I still have
> some Excel objects referenced within my code. Is this why the process
> doesn't terminate?
> 
> The related (I hope) parts of my code is here.
> 
> x1App = Dispatch("Excel.Application")
> Book1 = x1App.Workbooks.Open(ExcelLogPath+"\\outputLog-template.xls")
> x1App.Visible = 1
> for sheets in Book1.Worksheets:
>  if sheets.Name == file_name:
>   sheetExists = True
> if sheetExists != True:
>  activeSheet =
> Book1.Worksheets.Add(After=Book1.Worksheets(1))
>  activeSheet.Name = file_name
>  testNum[file_name] = 0
> Book1.Worksheets(file_name).Select()
> Book1.ActiveSheet.Cells(1+(testNum[file_name]*20),1).Value = "Original
> File Name"
> Book1.ActiveSheet.Cells(2+(testNum[file_name]*20),1).Value =
> file_name
> Book1.ActiveSheet.Pictures().Insert(output).Select()
> Book1.SaveAs(Filename=path)
> x1App.ActiveWorkbook.Close(SaveChanges=0)
> x1App.Quit()
> del x1App
> del Book1
> del activeSheet
> 
> What am I missing?
> 

In my Excel projects, I terminate it with:

xlBook.Close()
xlApp.Quit()

I haven't had a problem with Excel staying open after the program ends.

(On a tangent, I want to find the person who thought it was a good idea
to use the same symbol in a font for 1, l, and I and do some unpleasant
things.)


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


RE: newbie: stani's python editor if-else

2007-09-11 Thread Hamilton, William
> -Original Message-
> From: [EMAIL PROTECTED]
[mailto:python-
> [EMAIL PROTECTED] On Behalf Of
> [EMAIL PROTECTED]
> Sent: Tuesday, September 11, 2007 8:26 AM
> To: python-list@python.org
> Subject: Re: newbie: stani's python editor if-else
> 
> On Sep 10, 11:24 pm, madzientist <[EMAIL PROTECTED]> wrote:
> > hi,
> >
> > two quick questions:
> >
> > a) i am using SPE (latest version) and for some reason, when i type,
> > say
> >
> > if 1==2:
> > print "not equal"
> > else:
> >   print "equal"
> >
> > the else is at the same indentation level as the preceding print
> > statement, and i get a syntax error
> >
> > why doesn't spe automatically put the else at the level of the if
> > statement ? what am i dong wrong ? once i manually change the
> > indentation, the code snippet runs perfectly.
> >
> > b) if this is not the group for such elementary questions, please do
> > let me know.
> >
> > thanks 
> >
> > suresh
> 
> I agree with Steve. I have yet to see an IDE for Python (or anything
> else) that unindents statements. Even IDLE, the Official IDE for
> Python, doesn't do that.
> 

IDLE (At least, IDLE 1.0.5) unindents in obvious situations.  I think
it's only on break, continue, pass, and return statements, but there may
be others.

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


RE: Checking if elements are empty

2007-09-11 Thread Hamilton, William
> From: Steve Holden
> Neil Cerutti wrote:
> > On 2007-09-10, Chris Mellon <[EMAIL PROTECTED]> wrote:
> >> On 9/10/07, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> >>> Agreed; but I prefer 'if y[0] == ""', absent more context and
> >>> better names.
> >> Probably should use u"" if you're going to take that route, as
> >> this will fail spuriously if y[0] contains a unicode string
> >> that can't be implicitly converted to ascii. Personally, I
> >> prefer the boolean check and I'll let operations fail elsewhere
> >> if there's a type mismatch.
> >
> > I have a quibble not with the functionality of the boolean check,
> > but with its expressiveness. if y[0] == "" expresses more, i.e.,
> > that I expect y[0] to contain a Python byte string.
> >
> I have a quibble with a test that will raise an exception when the
> anticipated condition is true. Your test is patently absurd, as you
> would have discovered had you bothered to try it:
> 
>  >>> y = ""
>  >>> if y[0] == "":
> ...   print "True"
> ... else:
> ...   print "False"
> ...
> Traceback (most recent call last):
>File "", line 1, in 
> IndexError: string index out of range
>  >>>
> 
> Further, when the string is *not* the null string the test will always
> return False, as you will be comparing two strings of unequal length.
> 
> So, absent a solution that works, len(y) == 0 looks pretty good.


Going back to the OP, the problem is taking a string such as
>>> x = '  \t"ff'
then splitting that string like this
>>> y = x.split('\t')

The question is, does the first element of the list y contain an empty
string or not?  In this case, the logic in the following conditional is
perfectly valid.
>>> if y[0] == "":
...print "True"
... else
...print "False"

(len(y[0]) == 0) would also work, and is the solution you originally
gave the OP.  


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


RE: Silent SaveAs when using the Excel win32com module

2007-09-10 Thread Hamilton, William
> From: Chris
> 
> I'm trying to create an excel file which will act as a log, however I
> want to overwrite the file if it exists.
> 
> Looking at the SaveAs method I can't find anything that would allow
> it. I don't want the prompt to appear to ask whether to replace the
> file or not. I just want to replace it without thinking.
> 
> Thanks in advance.


Check if the file exists and delete it before saving the new one.
--
-Bill Hamilton
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: application version checking against database

2007-09-07 Thread Hamilton, William
> From: imageguy
> 
> We are trying to implement a system that checks the version of the
> application against a version number stored in the database.  We don't
> want the app and the db don't become out of sync.
> 
> We have tried setting a __version__ variable in the top most module,
> however, it seems that this is not accessible for the modules that are
> subsequently imported.  There are a several locations in the app where
> we want to do the version check, but we would like to have one place
> to set the version number, namely the top level module.
> 
> We have thought of creating a Version class and passing it around, but
> aren't really keen on that idea.
> 
> Any suggestions/ideas would be helpful.
> 
> 
> NOTE: the app is developed in wxPython.
> 

You could add a Version module that contains the version number and any
functions related to the version checking, and import that into the
modules that do version checking.

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


RE: list index()

2007-08-30 Thread Hamilton, William
> From: [EMAIL PROTECTED]
> >
> > How could it not be an exception, in the plain English sense of the
> > word? Most certainly you're asking for the index because you want to
do
> > something with the index. If the item is not found, you have no
index,
> > so that's a special case that must be handled separately. There is
no
> > logical difference between handling that special case in an except
> > clause versus handling it with an if-branch.
> 
> In my case of have done os.listdir() on two directories. I want to see
> what files are in directory A that are not in directory B.
> I have used exceptions in other languages and only do so on logic that
> should never happen. In this case it is known that some of the files
> will not be in both lists. I just want to know which ones.
> 

I think you may be confusing exceptions and assertions.  Asserts are
generally used to trap conditions that should not happen, while
exceptions in Python are a standardized way to handle errors of all
sorts.  Where in C you would, say, open a file and check the return code
to ensure that the file actually exists before using it, in Python you
wrap the open statement in a try/except block instead.


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


RE: Something in the function tutorial confused me.

2007-08-06 Thread Hamilton, William
> From: Lee Fleming
> On Aug 6, 12:30 pm, "Hamilton, William " <[EMAIL PROTECTED]> wrote:
> > When you call f(23), the variable y within it gets created and
points at
> > None.  When f(23) exits, the y that it created gets destroyed.
(Well,
> > goes out of scope, but even if it's not garbage collected it won't
ever
> > come back into scope.)  When you then call f(24), a new y is created
> > that also points to None, and disappears forever when f(24) exits.
> >
> > The values in a def statement are created when the def is executed,
but
> > the variables are only created when the function is actually called,
and
> > new ones are created every time the function is called.
> >
> > --
> > -Bill Hamilton- Hide quoted text -
> >
> > - Show quoted text -
> 
> why isn't the y in def f (x, y = []): something
> garbage-collected?
> 

The y is garbage-collected.  However, the [] in the def statement is
not.  The list is created when the statement is evaluated.  Every time
that f() is called with a default value, the new y created will point to
the same list.  If that list is mutated into [23], it will still be [23]
the next time f() is called, and the new y created in that call will
point at the same list (now [23]) that the (now destroyed) y pointed to
in the first call.

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


RE: Something in the function tutorial confused me.

2007-08-06 Thread Hamilton, William
> From: Lee Fleming
> 
> On Aug 6, 6:25 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> Because when the function is called,  the line
> 
> 
> > if y is None: y = []
> 
> 
> is executed, binding a brand new empty list to y. This
> "rebinding" happens every time the function is called, unless you
> provide an argument for y that is not None.
> 
> Thanks for the prompt replies. But I am still confused. This is what
> confuses me
> The first time you call the function, say with f(23), after the
> function ends,
> y no longer equals None. Therefore, calling f again, this time like
> this f(24),
> should make y equal [23,24], because the 'if y == None' test fails, or
> at least I think it
> fails, because y.append(x) added something that was not equal to None
> during the previous call.

When you call f(23), the variable y within it gets created and points at
None.  When f(23) exits, the y that it created gets destroyed.  (Well,
goes out of scope, but even if it's not garbage collected it won't ever
come back into scope.)  When you then call f(24), a new y is created
that also points to None, and disappears forever when f(24) exits.

The values in a def statement are created when the def is executed, but
the variables are only created when the function is actually called, and
new ones are created every time the function is called.

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


RE: Bug in Time module, or in my understanding?

2007-08-02 Thread Hamilton, William
> From: Joshua J. Kugler
> 
> I am getting results like these with the time module:
> 
> >>> import time
> >>> int(time.mktime(time.strptime('2007-03-11 02:00:00', '%Y-%m-%d
%H:%M
> %S')))
> 1173610800
> >>> int(time.mktime(time.strptime('2007-03-11 03:00:00', '%Y-%m-%d
%H:%M
> %S')))
> 1173610800
> >>> time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1173610800))
> '2007-03-11 03:00:00'
> 
> I know it probably has something to do with daylight savings, but how
can
> I
> get back out that which I put in?  The times concerned are all
standard
> time, so how can I keep the time module from asserting its belief that
I
> want to convert to daylight savings?
> 
> Incidentally, it only happens with times on 2007-03-11  from 02:00:00
to
> 02:59:59, and not with time data from past years.
> 

I get similar results, except with hours 01:00:00 and 02:00:00.  I am in
US Central time (GMT-6).

>>> int(time.mktime(time.strptime('2007-03-11 00:00:00','%Y-%m-%d
%H:%M:%S')))
1173592800
>>> int(time.mktime(time.strptime('2007-03-11 01:00:00','%Y-%m-%d
%H:%M:%S')))
1173596400
>>> int(time.mktime(time.strptime('2007-03-11 02:00:00','%Y-%m-%d
%H:%M:%S')))
1173596400
>>> int(time.mktime(time.strptime('2007-03-11 03:00:00','%Y-%m-%d
%H:%M:%S')))
117360


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


RE: Making Gridded Widgets Expandable

2007-07-30 Thread Hamilton, William
> From: Jim
> Hi,
> I'm looking at page 548 of Programming Python (3rd Edition) by Mark
> Lutz.
> The following GUI script works with no problem, i.e., the rows and
> columns expand:
> =
> # Gridded Widgets Expandable page 548
> 
> from Tkinter import *
> colors = ["red", "white", "blue"]
> 
> def gridbox(root):
> Label(root, text = 'Grid').grid(columnspan = 2)
> r = 1
> for c in colors:
> l = Label(root, text=c, relief=RIDGE, width=25)
> e = Entry(root, bg=c,   relief=SUNKEN, width=50)
> l.grid(row=r, column=0, sticky=NSEW)
> e.grid(row=r, column=1, sticky=NSEW)
> root.rowconfigure(r, weight=1)
> r += 1
> root.columnconfigure(0, weight=1)
> root.columnconfigure(1, weight=1)
> 
> root = Tk()
> gridbox(Toplevel(root))
> Button(root, text="Quit", command=root.quit).grid()
> mainloop()
> =
> However, the following GUI script using class does not expand rows and
> columns:
> =
> # Gridded Widgets Expandable 2
> 
> from Tkinter import *
> colors = ["red", "white", "blue"]
> 
> class GUI(Frame):
> def __init__(self,master):
> Frame.__init__(self,master)
> self.grid()
> self.gridbox()
> 
> def gridbox(self):
> Label(self, text = 'Grid').grid(columnspan = 2)
> r = 1
> for c in colors:
> l = Label(self, text=c, relief=RIDGE, width=25)
> e = Entry(self, bg=c,   relief=SUNKEN, width=50)
> l.grid(row=r, column=0, sticky=NSEW)
> e.grid(row=r, column=1, sticky=NSEW)
> self.rowconfigure(r, weight=1)
> r += 1
> self.columnconfigure(0, weight=1)
> self.columnconfigure(1, weight=1)
> 
> root = Tk()
> root.title("Gridded Widgets Expandable")
> app = GUI(root)
> Button(root, text="Quit", command=root.quit).grid()
> root.mainloop()
> =
> What am I missing?


In the first, your gridbox has Toplevel(root) as its master, causing it
to be created in a new window.  In the second, it has Frame(root) as its
master, which does not create a new window.  Changing Frame to Toplevel
in the class statement and the call to __init__ causes them to act
identically.


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


RE: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-05 Thread Hamilton, William
> From: Paul Rubin
> 
> greg <[EMAIL PROTECTED]> writes:
> > > E.g. your program might pass its test and run properly for years
> > > before some weird piece of input data causes some regexp to not
quite
> > > work.
> >
> > Then you get a bug report, you fix it, and you add a test
> > for it so that particular bug can't happen again.
> 
> Why on earth would anyone prefer taking a failure in the field over
> having a static type check make that particular failure impossible?
 

Because static typechecking won't make that particular failure
"impossible,"  but instead just change it from a type error into a data
error that may or may not be harder to identify.  If your program gets a
piece of data that breaks it, you'll get a failure in the field.  Static
typechecking won't prevent that.  


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


RE: Collections of non-arbitrary objects ?

2007-06-26 Thread Hamilton, William
> From: walterbyrd
> 
> 
> Yes, but those languages also have the notion of structures that do
> not allow arbitrary collections. That is what I was wondering about
> when I started the thread. It's fine that python has four different
> ways of creating collections of arbitrary data types, but I thought it
> might be helpful if python had, at least, one way of a creating a
> collection of non-arbitrary data.

The thing is, in python all data is arbitrary.  The differences between
the data types float, int, string, etc. are unimportant.  What is
important is the _behavior_ of those types.  

If it is really necessary to check data when putting it into your
collection (user input, processing side-effects will cause damage,
etc.), test that it behaves the way you need it to behave rather than
requiring a specific type.


> It seems to me that tuple are essentially immutable lists. So why
> impose that immutability restriction on a data collection? Why not
> just have lists and not tuples? What can a tuple do that a list can
> not do? Why was python designed so that tuples could be used for
> dictionary indexes, but not lists? Could it be because imposing that
> restriction on a data collection insures a certain degree of
> integrity? My point is: sometimes imposing some restrictions can give
> a degree in built-in integrity. Maybe you don't need that integrity
> insurance, if you code carefully enough, but can you always count on
> that?

Tuples are more like structs in C.  They are collections of data in a
particular order.  Lists, on the other hand, are ordered collections of
data that all exhibit the same behavior.  You don't have to use them
like that, but those are the uses they were developed for as I
understand it.

Function arguments are the obvious example of a tuple.  The position of
an argument in the argument tuple defines how it is used in the
function; get the position wrong, and the function will act unexpectedly
and probably raise an exception.  Iterating over a set of function
arguments doesn't make much sense in the general case.

Lists, are generally intended to be iterated over.  You may take a list
of items that are addable, and add them.  You may take a list of
file-like objects and concatenate them into one file-like object.  (And,
note the "-like" part of that.  They don't have to be files, they just
have to be things that _behave_ like files for the file-like functions
you'll be using.)


> BTW: I'm not assuming that it will always be me running my own app.
> Sure, if an exception occureed while I was running my own app, I'd
> probably know what to do. But if somebody else (who - god forbid -
> didn't know python was running the app, things might be more
difficult.

So, what happens when this user tries to put something into your
restricted list that isn't allowed?  I expect they'll produce an
exception of some sort, and the app will crash if you don't handle that
exception.  Which is exactly what will happen if you don't restrict the
list data and it gets processed.  


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


Excel file interface for Python 2.3?

2007-06-12 Thread Hamilton, William
I'm in need of a module that will let me create Excel workbooks from within
Python.  Something like PyExcelerator, but it needs to work with Python 2.3.
(A third-party limitation that I have no control over.)  Can anyone point me
to what I need?  All my searches keep leading back to PyExcelerator.

--
-Bill Hamilton
 

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


RE: c[:]()

2007-05-30 Thread Hamilton, William
> From: Warren Stringer
> Hmmm, this is for neither programmer nor computer; this is for a user. If
> I
> wanted to write code for the benefit for the computer, I'd still be
> flipping
> switches on a PDP-8. ;-)
> 
> This is inconsistent:
> 
> why does c[:][0]() work but c[:]() does not?
> Why does c[0]() has exactly the same results as c[:][0]() ?
> Moreover, c[:][0]() implies that a slice was invoked

c[:] is a copy of c, if c is a list, tuple, string, or other object that
supports slicing.  c[:][0] points to the same object as c[0].  If that
object is a function, then c[:][0]() and c[0]() do the same thing, because
they both point to the same function.

c[:]() does not make sense, because c is a tuple and not a function.
Similarly, c[0:1]() will not make sense because while c is a tuple of one
object, it is still a tuple and not a function.  Note that c[0] is not the
same as c[0:1]:  the former is the object pointed to by the first member of
the tuple, while the second is a tuple containing a single member pointing
to the first member of the original tuple.  There isn't an inconsistency
because the two notations mean completely different things.

> So, tell me, for scheduling a lot of asynchronous events, what would be
> more
> readable than this:
> 
>   bidders = [local_members] + [callin_members]
>   bidders[:].sign_in(roster)
>   ...

Does bidders[:].sort() make sense?  In your scheme, would this tell the
various contents of bidders to sort their own contents, or would it do the
currently valid action of sorting a copy of the bidders list?


I think you misunderstand how the slice operator works.  A slice of a tuple
is itself a tuple.  If you want to act on the contents of that tuple, you
need to act on those contents individually either by indexing them (c[0]) or
iterating over them (for f in c:).

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


RE: 'int' object is not callable in an threaded app

2007-05-22 Thread Hamilton, William
> From: king kikapu
> 
> Hi,
> 
> i have a problem with the following piece of code that id just drive
> me nuts (from the morning...)
> I think is more Python specific than Qt, folks from Qt forum have
> already give me directions of how to do it but that Python error
> message is just impossible for me to figure out. And i am sure that it
> something just under my nose...
> 
> So, i have a form with 2 spin boxes, a button and a progress bar. When
> i hit the button i expect to see the progressbar filled with the
> values of spFrom and spTo (the 2 spinboxes)
> 
> I was given help if how to setup correctly the Signals and Slots
> mechanism but i am stuck at this Python error at the "worker.start()"
> command:
> 
> TypeError: 'int' object is not callable
> 
> 
> Before i go and suicide, has anybody an idea what is going on
> here ??...
> 
> 
> 
> import sys
> from PyQt4 import QtCore, QtGui
> from calculatorform_ui import Ui_CalculatorForm
> from ui_countNumbers import Ui_MainWindow
> from time import sleep
> 
> class WorkerThread(QtCore.QThread):
> def __init__(self, start, end):
> QtCore.QThread.__init__(self)
> self.start = start
> self.end = end
> 
> def run(self):
> for x in range(start, end):
> self.emit(QtCore.SIGNAL("updateProgress"), x)
> 
> 
> class CountNumbersForm(QtGui.QMainWindow):
> def __init__(self, parent=None):
> QtGui.QMainWindow.__init__(self, parent)
> self.ui = Ui_MainWindow()
> self.ui.setupUi(self)
> 
> @QtCore.pyqtSignature("")
> def on_start_clicked(self):
> worker.start()
> 
> def updateProgress(self, val):
> self.ui.progres.setValue(val)
> 
> 
> if __name__ == "__main__":
> app = QtGui.QApplication(sys.argv)
> count = CountNumbersForm();
> worker = WorkerThread(count.ui.spFrom.value(),
> count.ui.spTo.value() + 1);
> QtCore.QObject.connect(worker, QtCore.SIGNAL("updateProgress"),
> count.updateProgress, QtCore.Qt.QueuedConnection)
> count.show()
> sys.exit(app.exec_())



It appears that worker.start gets set to the result of
count.ui.spFrom.value().  If that result is an int, then worker.start() is
going to generate the TypeError you received.  Did you actually mean to call
worker.run() instead?


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


RE: Installing Python in a path that contains a blank

2007-05-22 Thread Hamilton, William
> From: John Machin
> On 21/05/2007 11:30 PM, Konrad Hinsen wrote:
> > I am trying to install Python from sources in my home directory on a Mac
> > cluster (running MacOS X 10.4.8). The path to my home directory contains
> > a blank, and since the installation procedure insists on getting an
> > absolute path for the prefix, I cannot avoid installing to a path whose
> > name contains a blank. Python does not seem to be prepared for this, as
> > it uses only the part before the blank, resulting in numerous error
> > messages.
> >
> > Does anyone know a workaround?
> >
> 
> On Windows, the workaround for pesky paths (i.e. containing blanks or
> just inconveniently long) is the subst command:
> 
> command-prompt>subst X: "C:\Documents and Settings"
> 
> Thereafter X:\foo can be used wherever "C:\Documents and Settings\foo"
> would otherwise be required.

There's also short filename substitution.  "C:\Documents and Settings\foo"
can be replaced with "C:\docume~1\foo".  In general, you take the first six
non-space characters and append "~" to it.  I've never run into a
situation where  was anything other than 1, but I'm pretty sure that
you increment it if you have multiple files/directorys in the same directory
that have the same first six non-space characters.  This should work on any
Windows long-filename system where you need 8.3 filenames for backwards
compatibility.

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


RE: Random selection

2007-05-21 Thread Hamilton, William
> From: Tartifola
> Hi,
> I have a list with probabilities as elements
> 
> [p1,p2,p3]
> 
> with of course p1+p2+p3=1. I'd like to draw a
> random element from this list, based on the probabilities contained in
> the list itself, and return its index.
> 
> Any help on the best way to do that?
> Thanks

>>> ran = random.random()
>>> ran
0.70415952329234965
>>> for index, value in enumerate(x):
if sum(x[0:index]) > ran:
print index, ran
break


2 0.704159523292

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


RE: tkinter button state = DISABLED

2007-05-21 Thread Hamilton, William
> From: Eric Brunel
On Thu, 17 May 2007 09:30:57 +0200, Hendrik van Rooyen
> <[EMAIL PROTECTED]> wrote:
> >  "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> >> En Wed, 16 May 2007 03:22:17 -0300, Hendrik van Rooyen
> >>> I have never seen this working in Tkinter, unless the button was
> >>> pressed
> >>> on the
> >>> widget
> >>> in question - and worse, once you have clicked down on a ButtonRelease
> >>> binding
> >>> you can move the mouse pointer anywhere you like, even out of the
> >>> application
> >>> and when you release it, the bound function is called...
> >>>
> >>> Its either a bug or a feature, I don't know.
> >>
> >> Uhmm... I'm not sure I understand you completely. I only said that the
> >> "command" is fired only when the mouse button is pressed on the widget,
> >> AND released inside the same widget. If both events don't happen in the
> >> same widget, "command" won't fire. Maybe you are saying the same
> >> thing...
> >> anyway I'm not a Tk expert.
> >
> > No command is ok and you have described it right - its ButtonRelease
> that
> > seems broken to me
> 
> Apparently, this behaviour is the intended one, at least for buttons; see:
> http://www.tcl.tk/man/tcl8.4/TkCmd/bind.htm#M11
> 
> As for the question "why?", maybe you should ask it on the c.l.tcl
> newsgroup?

The difference between bind and the button's command parameter makes sense
to me.  You'd use bind to create something like a right-click menu, where
you want the same thing to happen whether the button is disabled or not.
You use the command parameter when you care about the state of the button.


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


RE: tkFileDialog.askopenfilename()

2007-05-16 Thread Hamilton, William
> From: [EMAIL PROTECTED]
> 
> Hi,
> When I call tkFileDialog.askopenfilename() , the dialog box opens with
> the current directory as the default directory. Is it possible to open
> the dialog box with a directory other than the current directory. Can
> we pass in  a user defined starting directory.
> Thanks
> Rahul
> 

This link has a decent amount of info about the various dialog modules.
http://www.pythonware.com/library/tkinter/introduction/x1164-data-entry.htm


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


RE: Trying to choose between python and java

2007-05-15 Thread Hamilton, William
> From: Beliavsky
On May 15, 1:30 am, Anthony Irwin <[EMAIL PROTECTED]> wrote:
> 
> 
> 
> > #5 someone said that they used to use python but stopped because the
> > language changed or made stuff depreciated (I can fully remember
> > which) and old code stopped working. Is code written today likely to
> > still work in 5+ years or do they depreciate stuff and you have to
> update?
> 
> Because Python 3 will change the syntax of print to disallow
> 
> print "Hello, world."
> 
> a substantial fraction of Python programs in existence, including all
> of my programs, will be broken. Draw your own conclusions.
> 

No, they'll work just fine.  They just won't work with Python 3.  It's not
like the Python Liberation Front is going to hack into your computer in the
middle of the night and delete you 2.x installation.

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


RE: keyword checker - keyword.kwlist

2007-05-10 Thread Hamilton, William
> From: [EMAIL PROTECTED]
> F:\Ohjelmat\Python25\Lib\keyword.pyc

That's your problem.  Rename keyword.py to keywordcheck.py, and delete
keyword.pyc in this directory, and it should work fine.

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


RE: keyword checker - keyword.kwlist

2007-05-10 Thread Hamilton, William
> From: [EMAIL PROTECTED]
> 
> Hi
> 
> I try to check whether a given input is keyword or not. However this
> script won't identify keyword input as a keyword. How should I modify it
> to make it work?
> 
> #!usr/bin/env python
> import keyword
> 
> input = raw_input('Enter identifier to check >> ')
> if input in keyword.kwlist:
>  print input + "is keyword"
> 
> else:
>  print input + "is not keyword"


It works fine for me.  Well, it did once I realized that 'keyword.py' was
not a good name to save the file under.  

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


RE: change of random state when pyc created??

2007-05-10 Thread Hamilton, William
> From: Alan Isaac
> 
> I'm sure my first pass will be flawed, but here goes:
> 
> http://docs.python.org/lib/typesmapping.html:
> to footnote (3), add phrase "which may depend on the memory location of
> the
> keys" to get:
> 
> Keys and values are listed in an arbitrary order,
> which may depend on the memory location of the keys.
> This order is non-random, varies across Python implementations,
> and depends on the dictionary's history of insertions and deletions.
> 
> http://docs.python.org/lib/types-set.html: append a new sentence to 2nd
> paragraph
> 
> Iteration over a set returns elements in an arbitrary order,
> which may depend on the memory location of the elements.

It's possible there are other factors that can affect this as well.  A more
general statement is probably more appropriate:

"Keys and values are listed in an arbitrary order.  This order is
non-random, varies across Python implementations, and depends on the
dictionary's history of insertions and deletions as well as factors outside
the scope of the containing program."

"Iteration over a set returns elements in an arbitrary order, which may
depend on factors outside the scope of the containing program."

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


RE: Simulating simple electric circuits

2007-05-09 Thread Hamilton, William
> From: Bjoern Schliessmann
> Sounds more familiar than the analog approach. Maybe I misunderstood
> something ... but I can't transfer my problem to this way of
> thinking yet. My biggest problem is the fact that relays aren't
> really interested in voltage, but current.
> 
> Also, I find it difficult to transfer this circuit logic to boolean
> logic I can contruct logic gates from. Sometimes, electric circuits
> are used in different directions.

You shouldn't have to worry about current degrading.  You apply a
current to the relay's coil, and it passes through the coil to ground
and triggers the relay.  The relay's outputs open or close connections
from the current source to the connected devices' inputs.  The only time
you'd have to worry about low currents is if a single relay is connected
to a lot of device inputs, because the current is split across the
inputs.

>From a logic standpoint, all you care about is whether each input and
output is on or off.


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


RE: Strange terminal behavior after quitting Tkinter application

2007-05-07 Thread Hamilton, William
> From: Chris
> > I'll admit to being surprised at seeing a claim that a
tkinter
> > application, started within an interactive session, without a
mainloop,
> > even runs... I could see it maybe happening from Idle, since Idle is
> > running a tkinter mainloop, so the application bindings may have
just
> > become "added widgets" to the Idle loop (but of course, a second
> > mainloop would conflict heavily).
> 
> You can try by building a working Tkinter GUI interactively from the
> standard Python interpreter, and see that the GUI works (i.e.
> processes events) at the same time.
> 


If you build it as a class (such as the code in Chris's original post)
it works; if you do it all directly, nothing happens until you run
mainloop().  It works, but I'm not sure that it was intended to work
that way.  I think your problem is related to that difference.

You'll probably be better off creating a new interpreter window as part
of your program, if you really need access to the interpreter alongside
your GUI.  You may be able to extract IDLE's interpreter window and use
it directly.


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


RE: How to check if a string is empty in python?

2007-05-04 Thread Hamilton, William
> -Original Message-
> From: [EMAIL PROTECTED]
> 
> On May 4, 5:02 am, Jaswant <[EMAIL PROTECTED]> wrote:
> > This is  a simple way to do it i think
> >
> > s=hello
> >
> > >>> if(len(s)==0):
> >
> > ... print "Empty"
> > ... else:
> > ... print s
> > ...
> > hello
> 
> But you are still making the assumption that s is a string.
> (BTW, you need quotes around your example.)
> 
> For example:
> 
> >>> print a,b
> 11 11
> 
> Can you tell which one is the string? I.e., which one had quotes
> around it?
> 
> If you correctly assume that it was b, then yes, your example works.
> 
> >>> print len(b)
> 2
> 
> If you incorrectly assume it was a, then the example doesn't work.
> 
> >>> print len(a)
> Traceback (most recent call last):
>   File "", line 1, in 
> print len(a)
> TypeError: object of type 'int' has no len()
> 
> You have to know that a variable is a string before you try to do a
> len().
> 
> Dynamic typing is a feature, but that doesn't relieve you of the
> necessary tests.

Your point would be important if the question were "How can I tell if x
is an empty string?"  On the other hand, "How to check if a string is
empty?" implies that the OP already knows it is a string.  Maybe he's
been using string methods on it, maybe he got it from a function that he
knows provides a string. Maybe he's checked its type.  It doesn't really
matter, if he's aware it is a string he doesn't have to test it for
stringness.


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


RE: Strange terminal behavior after quitting Tkinter application

2007-05-04 Thread Hamilton, William
> -Original Message-
> From: Chris
> Subject: Re: Strange terminal behavior after quitting Tkinter
application
> Clicking 'Quit' or on the window's 'x' causes the application to quit
> without messing up the terminal. With root.mainloop() commented out,
> though, no combination of root.quit(), root.destroy(), and sys.exit()
> stops the terminal from getting messed up.
> 
> So, I should call mainloop() for my application...except that I want
> to use the commandline, too, and calling mainloop() freezes the
> commandline. I wonder if there is another way to use the commandline
> and have a GUI? I couldn't find any clear information about that.
 

Can you run it in the background?  IIRC, if you put an ampersand ('&')
at the end of the command line, it will run as a background process and
leave your command line available for other tasks.  (The marker may be
something other than &, it's been a long, long time since I've used *nix
in a gui environment.)


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


RE: Dict Copy & Compare

2007-05-01 Thread Hamilton, William
> -Original Message-
> From: Steven D'Aprano
> Sent: Monday, April 30, 2007 10:14 PM
> To: python-list@python.org
> Subject: RE: Dict Copy & Compare
> 
> On Mon, 30 Apr 2007 12:50:58 -0500, Hamilton, William  wrote:
> 
> >> On quick question, how can I order a dict by the 'values' (not
keys)
> >> before
> >> looping? Is that possible?
> >>
> >
> > The easiest way I can think of is to create a new dict that's
reversed.
> >
> > reverseDict = {}
> > for key in dict1:
> > if dict1[key] not in reverseDict:
> > reverseDict[dict1[key]]=[key]
> > else:
> > reverseDict[dict1[key]].append(key)
> >
> > This gives you a dictionary that has the old dict's values as keys,
and
> > the old dict's keys as lists of values.  You can then sort the keys
of
> > this dict and do what you want with it.  Of course, the values in
dict1
> > have to be valid dictionary keys for this to work.  If they aren't,
you
> > may be able to get away with converting them to strings.
> 
> 
> Oh man, maybe you need to re-think what you consider "easier".
> 
> for value in dict1.itervalues()
> do_something_with(value)

This iterates through a list of values, with no information about the
keys at all.  Not particularly applicable to the OP's needs.
 
> If you need the keys as well:
> 
> for key, value in dict1.iteritems()
> do_something_with(key, value)

This iterates through values and keys, in no particular order.  Still
not useful.

> 
> If you need to process the values (say, sort them) first:
> 
> pairs = list(dict1.iteritems()) # or dict1.items()
> pairs.sort()
> for key, value in pairs:
> do_something_with(key, value)
> 
> I'll leave sorting by value instead of key as an exercise.

Hrmm.  Maybe you missed the part where the OP was asking how to sort a
dict's contents by value?  I'm pretty sure I quoted it.

My bit of code would be better if I had used iteritems() (I hadn't come
across that function yet).  But, it's a solution, and more useful than
vague statements about what someone else needs to rethink and various
bits of code that don't solve the problem presented.


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


RE: re-importing modules

2007-05-01 Thread Hamilton, William
> -Original Message-
> From: [EMAIL PROTECTED]
[mailto:python-
> [EMAIL PROTECTED] On Behalf Of John Nagle
> Sent: Monday, April 30, 2007 7:32 PM
> To: python-list@python.org
> Subject: Re: re-importing modules
> 
> [EMAIL PROTECTED] wrote:
> 
> >>In addition to the warning that reload() does not recursively reload
> >>modules that the reloaded module depends on, be warned that
reloading a
> >>module does not magically affect any functions or objects from the
old
> >>version that you may be holding on to.
> 
> Maybe reloading modules should be deprecated.  The semantics
> are awful, and it interferes with higher-performance implementations.
> 

I'd rather it weren't, personally.  I'm using Python with a third-party
application that provides an interactive prompt.  Removing reload()
would mean spending a good three minutes waiting for the application to
restart any time I make the slightest change in a module supporting that
application.  


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


RE: Dict Copy & Compare

2007-04-30 Thread Hamilton, William
> -Original Message-
> From: [EMAIL PROTECTED]
[mailto:python-
> [EMAIL PROTECTED] On Behalf Of Robert
Rawlins -
> Think Blue
> Sent: Monday, April 30, 2007 6:09 AM
> To: 'Tim Golden'
> Cc: python-list@python.org
> Subject: RE: Dict Copy & Compare
> 
> On quick question, how can I order a dict by the 'values' (not keys)
> before
> looping? Is that possible?
> 

The easiest way I can think of is to create a new dict that's reversed.

reverseDict = {}
for key in dict1:
if dict1[key] not in reverseDict:
reverseDict[dict1[key]]=[key]
else:
reverseDict[dict1[key]].append(key)

This gives you a dictionary that has the old dict's values as keys, and
the old dict's keys as lists of values.  You can then sort the keys of
this dict and do what you want with it.  Of course, the values in dict1
have to be valid dictionary keys for this to work.  If they aren't, you
may be able to get away with converting them to strings.



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


RE: import structures

2007-04-30 Thread Hamilton, William
> -Original Message-
> From: [EMAIL PROTECTED]
[mailto:python-
> [EMAIL PROTECTED] On Behalf Of spohle
> Sent: Monday, April 30, 2007 10:25 AM
> To: python-list@python.org
> Subject: Re: import structures
> 
> On Apr 30, 8:16 am, "Hamilton, William " <[EMAIL PROTECTED]> wrote:

> >
> > If you've got modules a, b, and c, you can create a wrapper module d
> > that imports from each of those.
> >
> > from a import *
> > from b import *
> > from c import *
> >
> > Then, import d and use it as the module name.  So if a had a
SomeThing
> > class, you could do this:
> >
> > import d
> > x = d.SomeThing()
> >
> > ---
> > -Bill Hamilton
> 
> 
> that doesn't seem to work for me. the from a import * will only give
> me a not d.a
> 


"from blah import *" puts everything in blah into the current module's
namespace (or so I understand it).  This is different from "import
blah":  with the latter, you have to use "x = blah.SomeThing()".  With
the former, you can simply say "x = SomeThing()".

So, if a has a class SomeThing, and you import it into d using "from a
import *", in d you can use SomeThing's methods directly.  If you then
use "import d" in your main script, you can create a SomeThing instance
with 
"x = d.SomeThing()".

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


RE: import structures

2007-04-30 Thread Hamilton, William
> -Original Message-
> From: [EMAIL PROTECTED]
[mailto:python-
> [EMAIL PROTECTED] On Behalf Of spohle
> Sent: Monday, April 30, 2007 10:03 AM
> To: python-list@python.org
> Subject: Re: import structures
> 
> On Apr 30, 8:00 am, Paul McGuire <[EMAIL PROTECTED]> wrote:
> > On Apr 30, 9:56 am, spohle <[EMAIL PROTECTED]> wrote:
> >
> >
> >
> > > hi,
> >
> > > i have written a small project for myself all in seperate classes
and
> > > each of the classes lives in a seperate file. now i am looking for
an
> > > import structure something like import wx, and then have access to
all
> > > my classes just like wx.Button or wx.BoxSizer etc.
> >
> > > as of now i have a __init__.py file in the directory with:
> > > from pkgutil import extend_path
> > > __path__ = extend_path(__path__, __name__)
> >
> > > but i still have to import each class by it's own. im really
looking
> > > for something like import wx
> > > and then get all my access right away under this new namespace.
> >
> > > thank you in advance
> >
> > If it really is a small project, consider just putting all the
classes
> > into a single module, say spohlePkg.py.  Then your users would
import
> > this module using "import spohlePkg", and would access the classes
as
> > "spohlePkg.ClassA", "spohlePkg.ClassB", etc.
> >
> > -- Paul
> 
> yeah i had that, but my classes grew really fast and i decided to
> split them up. but you're right that in one file that would solve my
> problem. still hoping to find a way for the seperate files.
> 

If you've got modules a, b, and c, you can create a wrapper module d
that imports from each of those.

from a import *
from b import *
from c import *


Then, import d and use it as the module name.  So if a had a SomeThing
class, you could do this:

import d
x = d.SomeThing()



---
-Bill Hamilton

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


RE: Python keywords

2007-04-26 Thread Hamilton, William
> -Original Message-
> From: [EMAIL PROTECTED]
[mailto:python-
> [EMAIL PROTECTED] On Behalf Of gtb
> Sent: Thursday, April 26, 2007 1:50 PM
> To: python-list@python.org
> Subject: Re: Python keywords
> 
> On Apr 26, 10:16 am, Larry Bates <[EMAIL PROTECTED]> wrote:
> > http://docs.python.org/ref/keywords.html
> >
> > in keyword is a general one and can be used for many objects.
> >
> > x in 'xyz'
> >
> > y in ['a','b','c','y','z'']
> >
> > z in ('a','b','c','y','z']
> >
> > key in {'key1':1, 'key2': 2}
> >
> > The in you see with a for isn't associated with the for loop
> > but rather the sequence you are iterating over
> >
> > for i in range(10):
> >
> > -Larry
> 
> Thanks Larry. I saw that page you referenced above and that is how I
> knew it was a keyword. But I still have found nodocumentation that
> supports the examples you provided.

http://docs.python.org/ref/comparisons.html#l2h-438

This information is 2 clicks away from any page in the reference:  click
the index link, then scroll down to the link to "in operator".


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


RE: Tutorial creates confusion about slices

2007-04-25 Thread Hamilton, William
> -Original Message-
> From: [EMAIL PROTECTED]
[mailto:python-
> [EMAIL PROTECTED] On Behalf Of Antoon
Pardon
> Sent: Tuesday, April 24, 2007 7:40 AM
> To: python-list@python.org
> Subject: Re: Tutorial creates confusion about slices
> 
> On 2007-04-24, Michael Bentley <[EMAIL PROTECTED]> wrote:
> >
> > On Apr 24, 2007, at 6:35 AM, Antoon Pardon wrote:
> >
> >> People don't read tutorials in a strictly linear fashion. They can
> >> continue to later subjects and then come back here to see how
things
> >> tie together. So the fact that it is only confusing to those who
> >> know more than is already presented doesn't seem a very good reason
> >> to leave it in.
> >
> > Yet they understand that earlier in the document, there is likely to
> > be a less complete coverage of a given topic.  There is in fact, a
> > link on that page that includes a more complete coverage of that
> > topic (which I mentioned to you in an earlier message IIRC).
> 
> That there is more complete coverage elsewhere is no good reason
> to come with an explanation that suggests things working in
> a way that will be contradicted by that more complete coverage.
> 
> Even after people have read the more complete coverage it is
> still very possible that they will come back to this part of
> the text and get the wrong idea of how things work.

That's how everything I've ever learned has been taught.  Start with a
simple explanation that may not be completely accurate but is
functional, then fill in the details later when there is a context to
put them in.  The tutorial could start out by explaining everything at
the implementation level; it doesn't because it is a _tutorial_,
intended to give new users the context they need to understand the more
complicated nuances of the language.  

If it covered every fiddly little detail, it wouldn't be a tutorial.  It
would be a language reference document instead.

> A more complete coverage elsewhere is not an adequate remedy
> for a tekst suggesting things working differently than they
> actually do. Sure in the long run people will figger out how
> things actually work and that the explanation given in that
> section is totally inadequate for negative steps. But I
> prefer that people don't loose too much time figgering out
> that a particular explanation only works for particular cases
> and not in general.
> 
> > Submit a patch if you want it changed.  I'm sure your valuable
> > insights will greatly improve the quality of the python
documentation.
> 
> Fat chance, if they reason like you.

So you're saying your insights aren't valuable?


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


RE: Tutorial creates confusion about slices

2007-04-23 Thread Hamilton, William
> -Original Message-
> From: [EMAIL PROTECTED]
[mailto:python-
> [EMAIL PROTECTED] On Behalf Of Antoon
Pardon
> Sent: Monday, April 23, 2007 7:38 AM
> To: python-list@python.org
> Subject: Tutorial creates confusion about slices
> 
> The following is part of the explanation on slices in the
> tutorial:
> 
> The best way to remember how slices work is to think of the indices as
> pointing between characters, with the left edge of the first character
> numbered 0. Then the right edge of the last character of a string of n
> characters has index n, for example:
> 
>   +---+---+---+---+---+
>   | H | e | l | p | A |
>   +---+---+---+---+---+
>   0   1   2   3   4   5
>  -5  -4  -3  -2  -1
> 
> This is all very well with a simple slice like:
> 
>   "HelpA"[2:4]=> "lp"
> 
> 
> But it give the wrong idea when using the following extended slice:
> 
>   "HelpA"[4:2:-1]   =>   "Ap"
> 
> So this doesn't result in the reverse of the previous expression while
> the explanation above suggest it does.
 
It makes sense if you recognize that the negative step value also flips
which "side" the index is on.  

   +---+---+---+---+---+
   | H | e | l | p | A |
   +---+---+---+---+---+
   0   1   2   3   4
  -6  -5  -4  -3  -2  -1


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


RE: Iterate through a dictionary of lists one "line" at a time

2007-04-18 Thread Hamilton, William
> -Original Message-
> From: [EMAIL PROTECTED]
[mailto:python-
> [EMAIL PROTECTED] On Behalf Of wswilson
> Sent: Wednesday, April 18, 2007 1:39 PM
> To: python-list@python.org
> Subject: Iterate through a dictionary of lists one "line" at a time
> 
> Here is my code:
> 
> listing = {'id': ['a', 'b', 'c'], 'name': ['Joe', 'Jane', 'Bob']}
> 
> I need to output:
> 
> id name
> a Joe
> b Jane
> c Bob
> 
> I could do:
> 
> print 'id', 'name'
> for id, name in zip(listing['id'], listing['name']): print id, name
> 
> but that only works if there are two entries in the dictionary, id and
> name, and I know what they are. My problem is I don't know how many of
> these entries there will be. Thanks for any help you can give!
> 

>>> for x in xrange(len(listing['id'])):
... print ""
... for key in listing.keys():
... print listing[key][x],


a Joe 
b Jane 
c Bob

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


RE: tuples, index method, Python's design

2007-04-11 Thread Hamilton, William
> -Original Message-
> From: [EMAIL PROTECTED]
[mailto:python-
> [EMAIL PROTECTED] On Behalf Of Chris Mellon
> Sent: Wednesday, April 11, 2007 9:12 AM
> To: python-list@python.org
> Subject: Re: tuples, index method, Python's design
>
>
> So, when you have a) a third party module that you cannot change and
> b) it shouldn't return a tuple but it does anyway and c) it's a big
> enough tuple that is large enough that conversion to a list is
> prohibitive, that's a "general" use case for tuple.index?
> 
> Has this supposedly general and common use case actually happened?

To me?  No.  Is it reasonable to believe it could happen?  Yes.  Is it
reasonable to say, "We don't think this is likely to happen often, so we
won't provide a simple way to deal with it?"  Well, I'm not a developer,
so it's not my decision.

---
-Bill Hamilton
[EMAIL PROTECTED]

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


RE: pop() clarification

2007-04-11 Thread Hamilton, William

> -Original Message-
> From: [EMAIL PROTECTED]
[mailto:python-
> [EMAIL PROTECTED] On Behalf Of Scott
>
> I understand all that.  What I don't understand is why all the
> documentation
> I see says, "When removing a specific element from a list using pop()
it
> must be in this format: list.pop([i]).
> At first I took that to mean that list.pop(i) would return some type
of
> error, but it doesn't.
> I can't find any documentation saying that this rule that I keep
reading
> about (again list.pop([i]) ) is the only format to use when removing a
> specific element because..with the explaination to follow.

I believe that the [i] notation is to indicate that it has to be a valid
index to your list.  If i isn't a valid index, you get an IndexError.

>>> spam=['this', 'is', 'a', 'list']
>>> spam.pop(1)
'is'
>>> spam.pop(4)

Traceback (most recent call last):
  File "", line 1, in -toplevel-
spam.pop(4)
IndexError: pop index out of range


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


RE: passing class by reference does not work??

2007-04-11 Thread Hamilton, William
> -Original Message-
> From: [EMAIL PROTECTED]
[mailto:python-
> [EMAIL PROTECTED] On Behalf Of wswilson
> Sent: Wednesday, April 11, 2007 9:24 AM
> To: python-list@python.org
> Subject: passing class by reference does not work??
> 
> Here is my code:
> 
> class A():
>   val = 0
> 
> def b(item, a):
>   a.val = a.val + 1
>   return item + a.val
> 
> def c():
>   d = [1, 2, 3]
>   print [b(item, A()) for item in d]
> 
> c()
> 
> I expected this to output [2, 4, 6]. However, it outputs [2, 3, 4]
> which is not what I wanted. I thought that if I passed the A()
> instance in my list comprehension in c(), then the changes I made to
> a.val in b() would be reflected in the A() instance next time the list
> comprehension called b(). But, obviously that is not happening. I'm
> kinda new at python so I may be missing something obvious here.
> 
> Any suggestions?

A() is not the class A.  It calls the constructor of class A, returning
an instance.  If you change that line to:

print [b(item, A) for item in d]

you'll get the output you expected.

---
-Bill Hamilton
[EMAIL PROTECTED]
 

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


RE: tuples, index method, Python's design

2007-04-11 Thread Hamilton, William
> -Original Message-
> From: [EMAIL PROTECTED]
[mailto:python-
> [EMAIL PROTECTED] On Behalf Of Steven
D'Aprano
> Sent: Wednesday, April 11, 2007 7:49 AM
> To: python-list@python.org
> Subject: Re: tuples, index method, Python's design
> 
> (There is one other option: you care that 32 is somewhere in the
tuple,
> but you don't care where. That's when you use the "in" operator.)
> 
> Anyway, that was the original design. When you see tuple, think
struct. If
> you have a struct, it doesn't make a whole lot of sense to ask "which
> field contains 32?", and so according to this intended usage, giving
> tuples index and count methods would be a Bad Idea: it just makes
extra
> work for the Python Dev team, for no benefit.
> 
> Personally, I think that tuples do double-duty as *both* immutable
lists
> and structs/records. So even though index and count methods don't make
> sense for a struct, it does make sense for an immutable list, and I
for
> one would not object to seeing tuples grow those two methods. 


>From another function, you receive a tuple of data that it extracted
from a stream.  Within that tuple is a marker that indicates where the
head of the incoming stream's data structure is.  You need to find the
marker and scan from that location on to sync your local data structure
to the incoming stream's data.  

Should the external function provide the stream data in a list rather
than a tuple?  Probably, but someone else wrote the function so that's
out of your control.  Can you cast the tuple to a list?  Sure, but for a
large tuple that's potentially a large speed and memory hit.

That probably the biggest general use case for tuple.index().  A
third-party module returns a tuple in which you need to find a piece of
data.


---
-Bill Hamilton
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Objects, lists and assigning values

2007-04-05 Thread Hamilton, William
-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of
Manuel Graune
Sent: Thursday, April 05, 2007 12:14 PM
To: python-list@python.org
Subject: Objects, lists and assigning values


Hello,

while trying to learn how to program using objects in python (up to now
simple scripts were sufficient for my needs) I stumbled over the
a problem while assigning values to an object.

The following piece of code shows what I intend to do:

<---snip--->

class new_class(object):
def __init__(   self,
internal_list=[]):
self.internal_list= internal_list

external_list=[[b*a for b in xrange(1,5)] for a in xrange(1,5)]
print external_list

first_collection=[new_class() for i in xrange(4)]

temporary_list=[[] for i in xrange(4)]
for i in xrange(4):
for j in xrange(4):
temporary_list[i].append(external_list[i][j])
first_collection[i].internal_list=temporary_list[i]


#Now everything is as I want it to be:
for i in xrange(4):
print first_collection[i].internal_list


#Now I tried to get the same result without the temporary
#variable:

second_collection=[new_class() for i in xrange(4)]

for i in xrange(4):
for j in xrange(4):
second_collection[i].internal_list.append(external_list[i][j])

#Which obviously leads to a very different result:

for i in xrange(4):
print second_collection[i].internal_list

<---snip--->

Can someone explain to me, what's happening here and why the two
approaches do not lead to the same results? Thanks in Advance.



Changing the definition of the class init function to:
def __init__(   self,
internal_list=None):
if internal_list:
self.internal_list= internal_list
else:
self.internal_list= []

fixes it.  The list in the default parameter of your version is created
once; every time an instance of the class is created, the
self.internal_list in that new class is assigned the same list instance
as all the other class instances.  When you append something to any of
those classes' lists, all of the classes' lists appear to change because
they're all actually the same list.

Your first_collection works because you're reassigning the class
parameter to a new list.  The second_collection doesn't work because
you're appending to the (flawed) existing list assignment.




---
-Bill Hamilton
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looping issues

2007-04-05 Thread Hamilton, William
-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of
[EMAIL PROTECTED]
Sent: Thursday, April 05, 2007 1:01 PM
To: python-list@python.org
Subject: Looping issues

What I am trying to do is compare two files to each other.

If the 2nd file contains the same line the first file contains, I want
to print it. I wrote up the following code:



correct_settings = open("C:\Python25\Scripts\Output
\correct_settings.txt","r")
current_settings = open("C:\Python25\Scripts\Output\output.txt","r")

for line in correct_settings:
for val in current_settings:
if val == line:
print line + " found."


correct_settings.close()
current_settings.close()


For some reason this only looks at the first line of the
correct_settings.txt file. Any ideas as to how i can loop through each
line of the correct_settings file instead of just looking at the first?

=
I think the problem is that it's actually only looping through
current_settings once; for the remaining lines in correct_settings,
current_settings is at EOF and produces nothing to be matched.

for line in correct_settings:
if line in current_settings:
print line + "found."

This may do what you want.

---
-Bill Hamilton
[EMAIL PROTECTED]

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


Project organization and import redux

2007-04-05 Thread Hamilton, William
I apologize for bringing up something that's a month dead.  But, I've
been reading through the recent archives and came across this
discussion, and want to make sure I understand a particular about the
interactive prompt.

"Martin Unsal"  wrote:
> I'm perfectly well aware that I'm not going to be able to reload a
> widget in the middle of a running GUI app, for example. I'm not
> looking for gotcha free, I'll settle for minimally useful.
>
> Here's an analogy. In C, you can do an incremental build and run your
> modified application without having to first reboot your computer. In
> Python, where reload() is essentially the incremental build process,
> and the interpreter is essentially a virtual machine, you guys are
> saying that my best option is to just "reboot" the virtual machine to
> make sure I have a "clean slate". It may be the path of least
> resistance, but to say that it is necessary or inevitable is 1960s
> mainframe thinking.

Yes, the interpreter is a virtual machine.  But the interactive prompt
is not a command line in that virtual machine.  Instead, it is the
statement that is about to be executed by a program running in that
virtual machine.  When you type a statement and press enter, that
statement is executed as the next line of the program.  It's analogous
to using a debugger to step through a C program line by line, except
you're providing those lines immediately rather than having to write and
compile them in advance.  

Restarting the interactive prompt isn't like rebooting the computer;
it's just restarting a program that is running on the computer.  At
worst, the interpreter is a computer that automatically shuts down when
the program running on it ends.


Is this a valid understanding of the workings of the interactive prompt,
or am I way off base?


---
-Bill Hamilton
[EMAIL PROTECTED]
 

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