Re: DTD Parsing

2010-11-09 Thread Ian Kelly

On 11/9/2010 11:14 PM, r0g wrote:

Me too when possible, TBH if I only needed strings and there was no
pressing security issue I'd just do this...

config = {}
for line in (open("config.txt", 'r')):
if len(line) > 0 and line[0] <> "#":
param, value = line.rstrip().split("=",1)
config[param] = value


That's five whole lines of code.  Why go to all that trouble when you 
can just do this:


import config

I kid, but only partially.  Where this really shines is when you're 
prototyping something and you need to configure complex object 
hierarchies.  No need to spend time writing parsers to generate the 
hierarchies; you just construct the objects directly in the config. 
When the project becomes mature enough that configuration security is a 
concern, then you can replace the config with XML or whatever, and in 
the meantime you can focus on more important things, like the actual 
project.


Cheers,
Ian

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


Am I The Only One Who Keeps Reading “Numpy” as “Numpty”?

2010-11-09 Thread Lawrence D'Oliveiro
Sorry...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Allowing comments after the line continuation backslash

2010-11-09 Thread Lawrence D'Oliveiro
In message <878w12kt5x.fsf@metalzone.distorted.org.uk>, Mark Wooding 
wrote:

> Lawrence D'Oliveiro  writes:
> 
>> Maybe you should look at the code in context
>> , then you can express some
>> more opinions on how to improve it.
> 
>   1. class keyval: `are there official symbolic names for these
>  anywhere?'  The gtk.keysyms module contains `Return', `KP_Enter',
>  `Left', `Up', `Right', and `Down'.

Thanks, that’s useful. I couldn’t find mention of such in the documentation 
anywhere.

>  Question: why are `returnkey' and `enterkey' defined in hex and the
>  others in decimal?

Can’t remember now. Does it matter?

>   2. The MainWindow class only has the `Window' attribute described in
>  its definition.  Apparently there are other attributes as well (the
>  ColorMumbleList family for one, also `LayerDisplay').  Similarly,
>  the LoadedImage class has attributes `Contents' and `FileName', but
>  I see attributes `RowStride', `ImageDrawSize' and `SrcDimensions'
>  used immediately below.

These are really just namespaces, one for the GUI context and the other for 
the image data.

>   3. In SelectSaveMenu, there's a curious `for' loop:
> 
> for State in (gtk.STATE_NORMAL,) : # no need for
> gtk.STATE_INSENSITIVE
>   ## blah
> 
>  Firstly, this is obviously equivalent to `state = gtk.STATE_NORMAL'
>  followed by the loop body (YAGNI).

It’s a tuple of one element. It used to be a tuple of two, and there is the 
possibility it might need to become that again (as intimated at in the 
attached comment). That’s why it stays a tuple.

>   4. Ahh!  I've tracked down where the MainWindow is actually
>  populated.  Ugh.  The code appears to revel in boilerplate.  (For
>  those at home, we're now looking at `SetupMainWindow', specifically
>  at the calls to `DefineScrollingList'.)  I count six calls, each
>  nearly (but not quite) identical, of about eleven lines each.

Could be worse. Imagine if I had written out the 30 lines of that function 
out each time instead.

>  Of course, being boilerplate, the similarities visually outweigh the
>  differences, when in fact it's the differences that are
>  interesting.

That is generally how code reuse works. All the “boilerplate” is in the 
function definition, so I just have to call it parameterized by the 
differences appropriate to each instance.

>  It doesn't help that all of the names of the things involved are so
>  wretchedly verbose.

Oh please, no. Since when are explanatory names “wretchedly verbose”?

>  How about the following?
> 
> def make_listview_l1 ...

And what, pray tell, is the significance of the name “make_listview_l1”? If 
there is something I would describe as “wretched”, it is the use of random 
numerical suffixes like this.

> Looking at some of the rest of the code, it might (or might not) be
> worthwhile actually making a class to gather together a list's model
> and view; subclasses can then vary their individual parameters, and
> the various colour lists can also keep the various captions with
> them.

Most of that variation is already handled without the limitations of 
thinking in classes. For example, selection of a colour in all three lists 
is handled through a single EditColor routine. And of course you’ve already 
seen how a single DefineScrollingList routine can be used to set up all the 
scrolling lists used in this GUI.

>   5. Much of the indentation and layout is rather unconventional, though
>  not intolerable.  But I found (deep in `SelectSaveMenu'):
> 
> NewRenderPixels = array.array \
>   (
> "B",
> FillColor
> *
> (ImageRowStride // 4 * ImageBounds[1])
>   )
> 
>   to be most disconcerting.

Is the structure of the expression not apparent to you? You’d probably need 
plenty of fresh air after something like this, then:

PatternArray = array.array \
  (
"I",
16 * (16 * (Light,) + 16 * (Dark,))
+
16 * (16 * (Dark,) + 16 * (Light,))
  )


>   Also, I couldn't work out why some parens are indented only two
>   spaces and others are indented the full eight.

Eight?? You mean four.

See, this is why I should probably stop using tabs...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Allowing comments after the line continuation backslash

2010-11-09 Thread Lawrence D'Oliveiro
In message , Robert Kern 
wrote:

> For me, putting the brackets on their own lines (and using a trailing
> comma) has little to do with increasing readability. It's for making
> editing easier. Keeping all of the items consistent means that in order to
> add, delete, or move any item is the same operation everywhere in the list
> whether it is the first item, last item, or any item in between.

Yup, I like to do that when there’s nothing special about the last item in 
the list. Sometimes there is (e.g. an enumeration entry naming the number of 
values in the enumeration, or an all-zero sentinel marking the end of a 
list), in which case I omit the comma to indicate that nothing should come 
afterwards.

I remember an early experience with JavaScript (back in the days of Netscape 
versus Internet Explorer 5.1 on a Mac), when I found that constructing a 
list in this way wasn’t working in IE: turned out it was inserting some kind 
of extra phantom list item after that last comma. Sigh...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Silly newbie question - Caret character (^)

2010-11-09 Thread Lawrence D'Oliveiro
In message , Seebs wrote:

> I may have my gripes about Python, but I will say this:  The Python
> community seems full of people who are passionate about writing good code.

And they know how to write good code in other languages, not just Python. In 
other words, they know programming, not just Python programming.

You see that come through a lot of the time, when a discussion goes off-
track like this. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DTD Parsing

2010-11-09 Thread r0g

On 10/11/10 03:36, Asun Friere wrote:

On Nov 10, 2:02 pm, Christian Heimes  wrote:

Am 10.11.2010 03:44, schrieb Felipe Bastos Nunes:


I'd like to know too. I work with java and jdom, but I'm doing
personal things in python, and plan to go full python in the next 2
years. Xml is my first option for configuration files and simple
storages.


Don't repeat the mistakes of others and use XML as a configuration
language. XML isn't meant to be edited by humans.


Yes but configuration files are not necessarily meant to be edited by
humans either!

Having said that, I'm actually old school and prefer "setting=value"
human editable config files which are easily read into a dict via some
code something like this:





Me too when possible, TBH if I only needed strings and there was no 
pressing security issue I'd just do this...


config = {}
for line in (open("config.txt", 'r')):
if len(line) > 0 and line[0] <> "#":
param, value = line.rstrip().split("=",1)
config[param] = value

There is a place for XML settings though, they're nice and portable and 
for some apps you probably don't want end users editing their 
configurations by hand in a text editor anyway, you would prefer them to 
use the nice consistency preserving config interface you have lovingly 
built for them. You have built them a nice GUI config interface haven't 
you ??? ;)


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


Re: DTD Parsing

2010-11-09 Thread Stefan Behnel

Asun Friere, 10.11.2010 06:41:

On Nov 10, 4:11 pm, Stefan Behnel wrote:


What's your interest in parsing a DTD if you're not up to validating XML?


Spitting out boilerplate code.
[...]
A few years back I used a similar technique to write some boiler plate
python code where xml was isomorphically represented on a class per
element basis (which will no doubt offend some people's sense of
generalisation, but is none the less an interesting way to work with
XML).


Give lxml.objectify a try. It doesn't use DTDs, but does what you want.

There are also some other similar tools like gnosis.objectify or Amara. I 
never benchmarked them in comparison, but I'd be surprised if 
lxml.objectify wasn't the fastest. I'd be interested in seeing the margin, 
though, in case anyone wants to give it a try.


It's generally a good idea to state what you want to achieve, rather than 
just describing the failure of an intermediate step of one possible path 
towards your hidden goal. This list has a huge history of finding shortcuts 
that the OPs didn't think of.


Stefan

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


Class extension confusion :(

2010-11-09 Thread r0g
I have a subclass of BaseHHTPRequestHandler which uses a dictonary 
"paths" and a function "api_call" which are defined in the main 
namespace of the module. I'd rather I was able to pass these object to 
the constructor and store them as data attributes "self.paths" and 
"self.api_call" but I'm not sure how to do that properly. My 
understanding is that one may extend a constructor by defining it's 
__init__ method, calling the parents constructor and then adding ones 
own attributes to taste. What I don't understand is where or how I am 
supposed to get these extra constructor arguments into the class given 
that I don't instantiate it myself, it is seemingly instantiated by 
HTTPServer class that I pass it to e.g.


httpd = HTTPServer(server_address, PlainAJAXRequestHandler)

I wondered if I ought to instantiate an instance of 
PlainAJAXRequestHandler, set the attributes (either manually or by 
extending it's constructor) and pass that to HTTPServer but I figured it 
expects a class not an instance as it probably wants to spawn one 
instance for each request so that would be a non starter. Might I need 
to subclass HTTPServer, find the bit that instantiates the request 
handler and override that so it passes it's constructor more parameters? 
Right now I'm pretty confused, can somebody please tell me how I might 
accomplish this, what I'm failing to grasp or point me to the docs that 
explain it - I've spent the last hour or two plowing through docs to no 
avail, I guess it's a case of keyword ignorance on my part! Code follows...


Thanks for reading!

Roger.



class PlainAJAXRequestHandler(BaseHTTPRequestHandler):

paths = { "/": pages.main,
  "/jqtest/": pages.jqtest
}

def do_GET(self):

# Handle JSON api calls
if self.path[:6] == "/ajax?":
getvars = urlparse.parse_qs( self.path[6:] )
api_key = getvars[ "api" ][0]
json_string = getvars[ "qry" ][0]
json_object = json.loads( json_string )
response = api_call( api_key, json_object )
if response:
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
self.wfile.write( response )
else:
self.send_response(404)
self.end_headers()
return

# Handle web pages
try:
page = self.paths[self.path]()
except KeyError:
self.send_response(404)
self.end_headers()
self.wfile.write( "404 - Document not found!" )
return
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write( page )
return
--
http://mail.python.org/mailman/listinfo/python-list


Re: DTD Parsing

2010-11-09 Thread Asun Friere
On Nov 10, 4:11 pm, Stefan Behnel  wrote:

> What's your interest in parsing a DTD if you're not up to validating XML?

Spitting out boilerplate code.

Just at the moment I'm creating a stub XSLT sheet, which creates a
template per element (from a 3rd party DTD with 143 elements, yuk!)
containing nothing more than a apply-templates line listing all
possible child elements and a comment saying 'NOT IMPLEMENTED: %s' %
element_name.  This saves not only typing, but helps me work through
and guards against any clumsy oversight on my part in writing a
translation sheet for an IMO overly large schema.

A few years back I used a similar technique to write some boiler plate
python code where xml was isomorphically represented on a class per
element basis (which will no doubt offend some people's sense of
generalisation, but is none the less an interesting way to work with
XML).

While I'm here and just for the record, (as I don't imagine anyone
would want to use the code I posted above), the line
"file_obj.close()" has no place in a function which is passed an open
file_object.  My apologies.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DTD Parsing

2010-11-09 Thread Stefan Behnel

Asun Friere, 10.11.2010 04:42:

On Nov 10, 2:02 pm, Christian Heimes wrote:


Back to the initial question: I highly recommend LXML for any kind of
XML processing, validation, XPath etc.


Sorry Christian, didn't realise at first that that was a response to
MY intial question.  But does lxml actually have something for parsing
DTDs, as opposed parsing XML and validating it against a DTD?


What's your interest in parsing a DTD if you're not up to validating XML?

Stefan

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


Re: Why "flat is better than nested"?

2010-11-09 Thread alex23
Gregory Ewing  wrote:
> I get it. Does that mean that I don't get it?

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


Re: Compare source code

2010-11-09 Thread Dan Stromberg
On Thu, Nov 4, 2010 at 10:45 AM, Tim Harig  wrote:

> I also looked at F# and Scala; but, neither are really applicable on my
> chosen platform.  With F# being such a new language, I suspect that it
> borrowed its indent practices either from Haskell or from Python.
>
I'm pretty sure F# gets its whitespace conventions from the ML family of
(very interesting) languages.  I believe F# is based largely on Objective
Caml.

http://stromberg.dnsalias.org/~strombrg/significant-whitespace.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Silly newbie question - Caret character (^)

2010-11-09 Thread Seebs
On 2010-11-10, Lawrence D'Oliveiro  wrote:
> What was sad to me to read  was this 
> phrase of yours:

> ... but rather, takes the shortest path to something that won't get
> those complaints anymore ...

> To me, this is the sign of someone who doesn't really enjoy what they do. 

Yes.

I both write and program, and I do them because I love them.  If I won
the lottery tomorrow (and hey, my chances are only very very slightly lower
than everyone else's), I wouldn't stop programming or writing.  I might
change my focus some, but both of them are things I'd keep doing.

> Because somebody who cares about what they do would take the trouble to get 
> it right. But if he can't be bothered, why does he keep doing it? There must 
> be more pleasant ways of getting a meal ticket...

It's hard to say.  I get the feeling sometimes that he's one of the people
to whom programming is sort-of-fun, but not fun when you have to get all
persnickety about it.  Similarly, writing is fun if you're getting praised
for it, but dealing with criticism is harder.  (Trust me, I know of this;
I have gotten a fair number of corrections over the years.)

That said, I suspect he's made a fairly large amount of money; multiple
bestsellers is a pretty good way to make a decent bit of pocket change.

I may have my gripes about Python, but I will say this:  The Python community
seems full of people who are passionate about writing good code.  I would
much rather be in a community of people who care a lot about how I should
do things, but I think they're wrong, than about people who figure anything
that the interpreter accepts is fine.  I can learn from people I disagree
with, but not from people who don't care.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Silly newbie question - Caret character (^)

2010-11-09 Thread Lawrence D'Oliveiro
In message , Seebs wrote:

> In particular, he's very good at making up complications from whole cloth
> which aren't really problems, and then offering "solutions" which show
> people a clever trick to work around the problem.  (e.g., his elaborate
> revelations about how to use feof() in C to work around his failure to
> understand how EOF works.)

What was sad to me to read  was this 
phrase of yours:

... but rather, takes the shortest path to something that won't get
those complaints anymore ...

To me, this is the sign of someone who doesn’t really enjoy what they do. 
Because somebody who cares about what they do would take the trouble to get 
it right. But if he can’t be bothered, why does he keep doing it? There must 
be more pleasant ways of getting a meal ticket...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Commercial or Famous Applicattions.?

2010-11-09 Thread Lawrence D'Oliveiro
In message , Martin Gregorie wrote:

> ...and don't forget getmail, a better behaved replacement for fetchmail.

I was just looking this up in the Getmail FAQ, since I didn’t know about the 
issues with Fetchmail.

That’s it, ESR is off my Christmas-card list...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DTD Parsing

2010-11-09 Thread Asun Friere
On Nov 10, 2:02 pm, Christian Heimes  wrote:

> Back to the initial question: I highly recommend LXML for any kind of
> XML processing, validation, XPath etc.

Sorry Christian, didn't realise at first that that was a response to
MY intial question.  But does lxml actually have something for parsing
DTDs, as opposed parsing XML and validating it against a DTD?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DTD Parsing

2010-11-09 Thread Asun Friere
On Nov 10, 2:02 pm, Christian Heimes  wrote:
> Am 10.11.2010 03:44, schrieb Felipe Bastos Nunes:
>
> > I'd like to know too. I work with java and jdom, but I'm doing
> > personal things in python, and plan to go full python in the next 2
> > years. Xml is my first option for configuration files and simple
> > storages.
>
> Don't repeat the mistakes of others and use XML as a configuration
> language. XML isn't meant to be edited by humans.

Yes but configuration files are not necessarily meant to be edited by
humans either!

Having said that, I'm actually old school and prefer "setting=value"
human editable config files which are easily read into a dict via some
code something like this:

def read_config (file_obj) :
"""Reads a config file and returns values as a dictionary

Config file is a series of lines in the format:
#comment
name=value
name:value
name = value #comment
Neither name nor value may contain '#', '=', ':' nor any spaces.

"""
config = {}
nameval = re.compile('^\s*([^=:\s]+)\s*(?:=|:)\s*([^=:\s]*)
\s*(?:#.*)?\s*$').search
comment = re.compile('^\s*($|#)').search
for line in file_obj :
if comment(line) : continue
try :
name, value = nameval(line).groups()
except AttributeError :
sys.stderr.write('WARNING: suspect entry: %s\n' % line)
continue
config[name]=value
file_obj.close()
return config

Thanks Christian, I might check out 'configobj', but my needs are
rarely more complicated than the above will satisfy.

In any case Felipe, whether you intend to use XML for config or not
(or for any other reason), there are good tools for XML parsing in
python including with DTD validation.  Try the modules 'libxml2',
'lxml', or even, if your needs are modest, the poorly named
'HTMLParser'.

What I'm looking for instead is something to parse a DTD, such as
xmlproc's DTDConsumer.  It might even exist in the modules I've
mentioned, but I can't find it.  In the event, I think I'll use a DTD-
>xsd conversion script and then simply use HTMLParser.  Unless someone
can point me in the way of a simple DTD parser, that is.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Allowing comments after the line continuation backslash

2010-11-09 Thread Robert Kern

On 2010-11-09 19:39 , Mark Wooding wrote:

Tim Chase  writes:


On 11/09/10 18:05, Robert Kern wrote:

For me, putting the brackets on their own lines (and using a
trailing comma) has little to do with increasing readability. It's
for making editing easier.


It also makes diff's much easier to read (my big impetus for doing the
same as Robert)


Hmm.  That's a good point, actually.  I'm not overly fussed about the
ease of editing: it doesn't seem especially hard either way.


It might just be my vim bias. Vim has such *very* easy ways to cut and paste 
whole lines that not taking the opportunity to permit them seems like a waste.


--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: DTD Parsing

2010-11-09 Thread Christian Heimes
Am 10.11.2010 03:44, schrieb Felipe Bastos Nunes:
> I'd like to know too. I work with java and jdom, but I'm doing
> personal things in python, and plan to go full python in the next 2
> years. Xml is my first option for configuration files and simple
> storages.

Don't repeat the mistakes of others and use XML as a configuration
language. XML isn't meant to be edited by humans. It's my strong believe
that XML is great for stuff like data exchange and long time data
storage, but not for configuration.

Python has much more suited ways to deal with configuration. At work we
used to have XML for configuration years ago. Today we use configobj
[1], a ini style config system with config specs, validation and many
more features. You can define a setting as e.g. list of ints and you
actually get a list of ints from the resulting config object.

Back to the initial question: I highly recommend LXML for any kind of
XML processing, validation, XPath etc. It's super fast, extremely
powerful and supports all features of libxml2 and libxslt. It also
supports DTD, RelaxNG and XML schema.

Christian

[1] http://pypi.python.org/pypi/configobj
[2] http://pypi.python.org/pypi/lxml

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


Re: DTD Parsing

2010-11-09 Thread Felipe Bastos Nunes
I'd like to know too. I work with java and jdom, but I'm doing
personal things in python, and plan to go full python in the next 2
years. Xml is my first option for configuration files and simple
storages.

2010/11/10, Asun Friere :
> Now that PyXML (and thus xmlproc) is defunct, does anyone know any
> handy modules (apart from re :) for parsing DTDs?
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Felipe Bastos Nunes
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Allowing comments after the line continuation backslash

2010-11-09 Thread Tim Chase

On 11/09/10 19:39, Mark Wooding wrote:

Tim Chase  writes:

It also makes diff's much easier to read


Hmm.  That's a good point, actually.  I'm not overly fussed
about the ease of editing: it doesn't seem especially hard
either way.  But nice diffs are definitely valuable.  Food for
thought; thanks.


I find that diffs like

  for row in (
  (item_bar, details_bar),
  (item_foo, details_foo),
+ (item_baz, details_baz),
  ):
do_something(row)

are much easier/faster to understand instead of

  for row in (
  (item_bar, details_bar),
- (item_foo, details_foo)):
+ (item_foo, details_foo),
+ (item_baz, details_baz)):
do_something(row)


-tkc



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


DTD Parsing

2010-11-09 Thread Asun Friere
Now that PyXML (and thus xmlproc) is defunct, does anyone know any
handy modules (apart from re :) for parsing DTDs?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Allowing comments after the line continuation backslash

2010-11-09 Thread Mark Wooding
Tim Chase  writes:

> On 11/09/10 18:05, Robert Kern wrote:
> > For me, putting the brackets on their own lines (and using a
> > trailing comma) has little to do with increasing readability. It's
> > for making editing easier.
>
> It also makes diff's much easier to read (my big impetus for doing the
> same as Robert)

Hmm.  That's a good point, actually.  I'm not overly fussed about the
ease of editing: it doesn't seem especially hard either way.  But nice
diffs are definitely valuable.  Food for thought; thanks.

-- [mdw]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Allowing comments after the line continuation backslash

2010-11-09 Thread Tim Chase

On 11/09/10 18:05, Robert Kern wrote:

For me, putting the brackets on their own lines (and using a trailing comma) has
little to do with increasing readability. It's for making editing easier.


It also makes diff's much easier to read (my big impetus for 
doing the same as Robert)


-tkc


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


Re: Pythonic/idiomatic?

2010-11-09 Thread Robert Kern

On 11/8/10 8:13 PM, Seebs wrote:

On 2010-11-09, Ben Finney  wrote:

Seebs  writes:

I think we're stuck with backwards compatibility at least as far as
2.4.



Then you don't yet have the ???any??? and ???all??? built-in functions, or the
tuple-of-prefixes feature of ???str.startswith??? either. Bummer.


Eww.


At which point, the Pythonic thing to do is to convince your
organisation to use a version of Python that's at least officially
supported by the PSF :-)


Unfortunately, we're selling something to people who will explode if
we tell them to upgrade their RHEL4 systems, so we have to work on those.
(There is some tiny hope that we'll be able to move the baseline to RHEL5
within another two years.)


When we deal with such people, we also sell them a recent Python interpreter. 
:-)

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Pythonic/idiomatic?

2010-11-09 Thread Martin Gregorie
On Wed, 10 Nov 2010 00:11:23 +, Seebs wrote:

> On 2010-11-09, Jean-Michel Pichavant  wrote:
>> One pythonic way to do it, is to use an option parser.
> 
> That seems like massive overkill -- I don't care about any of the other
> options.  It seems like it'd result in doing more work to get and then
> extract the options, and most of that would be discarded instnatly.
>
I've always used an extended version of getopt() in C. I was so surprised 
to see that there's nothing equivalent in Java that I wrote my own and 
was consequently was very pleased to find that Python already has the 
optparse module. Using it is a no-brainer, particularly as it makes quite 
a good fist of being self-documenting and of spitting out a nicely 
formatted chunk of help text when asked to do so.


-- 
martin@   | Martin Gregorie
gregorie. | Essex, UK
org   |
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Silly newbie question - Caret character (^)

2010-11-09 Thread Seebs
On 2010-11-09, Terry Reedy  wrote:
> I've been wondering why C programmers keep writing code susceptible to 
> buffer overruns ;=).

Because we're dumb!

(Actually, in my defense, my code almost never, if ever, has buffer 
overruns.  I do in some rare cases have truncation issues with sufficiently
ridiculous input data.)

> Your two 'nitpicks' about fflush have both come up on this list as real 
> issues causing people problems. So I agree that it needs to be explained 
> properly and completely as you suggest.

Huh.  Since Schildt fell out of favor, I've almost never seen people trying
to fflush(stdin), and the update rules are weird enough that I don't think
I've ever seen anyone try to use it.  :)

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic/idiomatic?

2010-11-09 Thread Seebs
On 2010-11-09, Jean-Michel Pichavant  wrote:
> One pythonic way to do it, is to use an option parser.

That seems like massive overkill -- I don't care about any of the other
options.  It seems like it'd result in doing more work to get and then
extract the options, and most of that would be discarded instnatly.

-s
-- 
Copyright 2010, all wrongs reversed.  Peter Seebach / usenet-nos...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!
I am not speaking for my employer, although they do rent some of my opinions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Allowing comments after the line continuation backslash

2010-11-09 Thread Robert Kern

On 11/9/10 4:51 PM, Mark Wooding wrote:

Lawrence D'Oliveiro  writes:


In message<87fwvdb69k.fsf@metalzone.distorted.org.uk>, Mark Wooding
wrote:

for descr, attr, colours in [
 ('normal',  'image','Normal'),
 ('highlighted', 'highlight','Highlighted'),
 ('selected','select',   'Selected')]:
   colourlist = getattr(MainWindow, 'Colors%sList' % colours)
   ## ...


But then you lose the ability to match up the bracketing symbols.


You're right.  I do.


That’s why I put them on lines by themselves.


But the bracketing symbols are thoroughly uninteresting!  All that
putting them on their own lines achieves is to draw attention to the
scaffolding at the expense of the building.  It's great if you like the
Pompidou Centre, I suppose...


For me, putting the brackets on their own lines (and using a trailing comma) has 
little to do with increasing readability. It's for making editing easier. 
Keeping all of the items consistent means that in order to add, delete, or move 
any item is the same operation everywhere in the list whether it is the first 
item, last item, or any item in between.


--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: python script installation wizard

2010-11-09 Thread Ian Kelly
On Tue, Nov 9, 2010 at 3:43 PM, macro coders  wrote:

>
> i want simple "hello world" script. i want python installer. sample image
> http://img705.imageshack.us/img705/9430/py2exe.png   how do python setup
> wizard?
>

Use the distutils package in the standard library.  You'll need to write a
setup.py file for your distribution, and the Windows installer will be
created using the "setup.py bdist_wininst" command.  See the distutils
documentation for the details.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Allowing comments after the line continuation backslash

2010-11-09 Thread Mark Wooding
Lawrence D'Oliveiro  writes:

> In message <87fwvdb69k.fsf@metalzone.distorted.org.uk>, Mark Wooding
> wrote:
> > for descr, attr, colours in [
> > ('normal',  'image','Normal'),
> > ('highlighted', 'highlight','Highlighted'),
> > ('selected','select',   'Selected')]:
> >   colourlist = getattr(MainWindow, 'Colors%sList' % colours)
> >   ## ...
>
> But then you lose the ability to match up the bracketing symbols. 

You're right.  I do.

> That’s why I put them on lines by themselves.

But the bracketing symbols are thoroughly uninteresting!  All that
putting them on their own lines achieves is to draw attention to the
scaffolding at the expense of the building.  It's great if you like the
Pompidou Centre, I suppose...

Besides, any editor worth its salt will highlight bracket mismatches for
the reader, or at least get its automatic indentation in a twist if you
get the brackets wrong.

> Maybe you should look at the code in context
> , then you can express some
> more opinions on how to improve it.

  1. class keyval: `are there official symbolic names for these
 anywhere?'  The gtk.keysyms module contains `Return', `KP_Enter',
 `Left', `Up', `Right', and `Down'.  Question: why are `returnkey'
 and `enterkey' defined in hex and the others in decimal?

  2. The MainWindow class only has the `Window' attribute described in
 its definition.  Apparently there are other attributes as well (the
 ColorMumbleList family for one, also `LayerDisplay').  Similarly,
 the LoadedImage class has attributes `Contents' and `FileName', but
 I see attributes `RowStride', `ImageDrawSize' and `SrcDimensions'
 used immediately below.

  3. In SelectSaveMenu, there's a curious `for' loop:

for State in (gtk.STATE_NORMAL,) : # no need for gtk.STATE_INSENSITIVE
  ## blah

 Firstly, this is obviously equivalent to `state = gtk.STATE_NORMAL'
 followed by the loop body (YAGNI).  Secondly, the loop is followed
 by an `#end if' comment.  If you're going to write the things, at
 least get them right!

  4. Ahh!  I've tracked down where the MainWindow is actually
 populated.  Ugh.  The code appears to revel in boilerplate.  (For
 those at home, we're now looking at `SetupMainWindow', specifically
 at the calls to `DefineScrollingList'.)  I count six calls, each
 nearly (but not quite) identical, of about eleven lines each.  Of
 course, being boilerplate, the similarities visually outweigh the
 differences, when in fact it's the differences that are
 interesting.

 It doesn't help that all of the names of the things involved are so
 wretchedly verbose. How about the following?

def make_listview(label, render, colattr, head, bounds, osc, box):
  setattr(MainWindow, label + 'Display',
  DefineScrollingList(getattr(MainWindow, label + 'List'),
  0, render, colattr, head,
  bounds, osc, box)
  
def make_listview_l1(label, head, osc):
  make_listview(label, None, 'text, head, (160, 160), osc, List1Box)
make_listview_l1('Button', 'Buttons', None)
make_listview_l1('Layer', 'Button Layer', LayerSelectionChanged)

MainWindow.colourlist = {}
MainWindow.colourview = {}
for head in ['Normal', 'Highlight', 'Select']:
  MainWindow.colourlist[head] = gtk.ListStore(gobject.TYPE_PYOBJECT)
  MainWindow.colourview[head] = \
DefineScrollingList(MainWindow.colourlist[head],
0, ColorCellRenderer(), None,
head, (120, 120), None, List2Box)

make_listview('LoadedColors', ColorCellRenderer(), None, '',
  (120, 240), None, MiddleBox)

Looking at some of the rest of the code, it might (or might not) be
worthwhile actually making a class to gather together a list's model
and view; subclasses can then vary their individual parameters, and
the various colour lists can also keep the various captions with
them.  (Sometimes a strong separation between model and view is a
good thing; this doesn't seem to be one of those times.)

  5. Much of the indentation and layout is rather unconventional, though
 not intolerable.  But I found (deep in `SelectSaveMenu'):

NewRenderPixels = array.array \
  (
"B",
FillColor
*
(ImageRowStride // 4 * ImageBounds[1])
  )

  to be most disconcerting.  Also, I couldn't work out why some
  parens are indented only two spaces and others are indented the
  full eight.  Oh!  It's inconsistent tab/space selection.

I'm afraid that about this point I had to get on with some other stuff.

I've done enough throwing of stone

Re: Silly newbie question - Caret character (^)

2010-11-09 Thread Lawrence D'Oliveiro
In message , Terry Reedy 
wrote:

> Your two 'nitpicks' about fflush have both come up on this list as real
> issues causing people problems.

Cache on disk drives is a bug, not a feature. Performance-wise, it’s fast 
RAM hobbled by being located on the wrong side of a connection to the CPU 
that isn’t designed to transfer data at RAM speeds. And of course 
correctness-wise, it’s another complication in implementing the semantics of 
OS operations that are supposed to guarantee that data has been saved to 
persistent storage.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Pyhton - Functional Programming - How intersect/difference two dict with dict/values? fast!

2010-11-09 Thread macm
Sorry Mr. Nagle and Folks

I had a bad day today.

I need forward but with fever, a grasp and headache is hard.

You are absolute right, I was rude and I ask your pardon.

About my code, sorry I thought was the best way to copy and paste in
python console.

Best Regards

macm

On Nov 9, 7:03 pm, "D'Arcy J.M. Cain"  wrote:
> On Tue, 09 Nov 2010 15:55:16 -0500
>
> Terry Reedy  wrote:
> > To echo John Nagle's point, if you want non-masochist volunteers to read
> > your code, write something readable like:
>
> > dict1 = {'ab': [[1,2,3,'d3','d4',5], 12],
> >           'ac': [[1,3,'78a','79b'], 54],
> >           'ad': [[56,57,58,59], 34],
> >           'ax': [[56,57,58,59], 34]}
>
> I have been learning to like this form:
>
> dict1 = dict(
>   ab = [[1,2,3,'d3','d4',5], 12],
>   ac = [[1,3,'78a','79b'], 54],
>   ad = [[56,57,58,59], 34],
>   ax = [[56,57,58,59], 34],
> )
>
> Of course, it only works when all the keys are strings.
>
> --
> D'Arcy J.M. Cain          |  Democracy is three 
> wolveshttp://www.druid.net/darcy/               |  and a sheep voting on
> +1 416 425 1212     (DoD#0082)    (eNTP)   |  what's for dinner.

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


python script installation wizard

2010-11-09 Thread macro coders
i want simple "hello world" script. i want python installer. sample image
http://img705.imageshack.us/img705/9430/py2exe.png   how do python setup
wizard?
-- 
*Www.PythonTR.Org*
-macrocoders-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Silly newbie question - Caret character (^)

2010-11-09 Thread Lawrence D'Oliveiro
In message , Terry Reedy 
wrote:

> I've been wondering why C programmers keep writing code susceptible to
> buffer overruns ;=).

I am continually disappointed with the ‘do as I say, not as I do” attitude 
among people offering up sample code. I remember writing to one contributor 
to a programming magazine many years ago, about his admonition not to simply 
copy-and-paste sample code, to point out that he had done exactly that 
(complete with bug).

The main sticking point seems to be error checking; for some reason, writers 
of sample code seem to believe the code is “clearer” if you leave this out, 
when in fact all real-world applications of the illustrated techniques would 
include the error checks. So what do they end up illustrating? Nothing 
relevant to the real world.

Is this why so many real-world programs fail to check for errors in 
important places, and segfault or behave unpredictably instead of gracefully 
reporting a problem?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Silly newbie question - Caret character (^)

2010-11-09 Thread Lawrence D'Oliveiro
In message <87pquekxbe.fsf@metalzone.distorted.org.uk>, Mark Wooding 
wrote:

> The book was much cheaper than a copy of the C standard from ANSI or ISO
> even when it was new.  It was a common joke (HHOS) at the time that the
> difference in price reflected the value of the annotations.

Crapware in a book! :)

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


Re: populating a doubly-subscripted array

2010-11-09 Thread Mark Wooding
Gregory Ewing  writes:

> A reasonably elegant way to fix this is to use list comprehensions
> for all except the innermost list:
>
>ff = [[0.0]*5 for i in xrange(5)]

Yes, this is a good approach.  I should have suggested something like
this as a solution myself, rather than merely explaining the problem.

> If you're computing heavily with arrays, you might also consider
> using numpy arrays instead of lists.

Also a good idea.

-- [mdw]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary of lists strange behaviour

2010-11-09 Thread John Posner

On 11/9/2010 1:43 PM, Terry Reedy wrote:

... List *is* useful as an initializer for
collecitons.defaultdicts.


And it was useful when several members of this forum helped me to 
develop a prime-number generator.


See http://www.mail-archive.com/python-list@python.org/msg288128.html.

(I meant to post this to the "functions, list, default parameters" 
thread, but never got a round tuit.)


-John





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


Kareena and Saif Kissing I Kurbaan sex scene | Kareena Topless Kiss | Kurbaan Kiss

2010-11-09 Thread Sana Khan
http://groups.google.com/group/hsfun/t/8c6133cfeac2eff0
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subclassing str

2010-11-09 Thread Mark Wooding
rantingrick  writes:

> One thing i love about Python is the fact that it can please almost
> all the "religious paradigm zealots" with it's multiple choice
> approach to programming. However some of the features that OOP
> fundamentalists hold dear in their heart are not always achievable in
> a clean manner with Python. Yes you could use a function but that is
> not the OOP way.

It can be more than just an aesthetic difference.  Sometimes it can be
nice to extend existing classes to understand additional protocols.  For
example, suppose you're implementing some object serialization format:
it'd be really nice if you could add `serialize' methods to `str',
`int', `list' and friends.  This is certainly the Smalltalk way.
Unfortunately, you can't do it in Python.

One option is to implement a subclass which implements the additional
protocol.  This causes fragmentation: now each protocol wants its own
subclass: if you want an object which understands both protocols, you
need to mess with multiple inheritance[1] (and, in Python, at least,
hope that everyone is using `super' properly to implement upwards
delegation).

Otherwise you have to do the dispatch yourself, either by hand or by
using one of the generic function/multimethod frameworks.

[1] At least Python gives you a fighting chance of getting this to work.
Java and C# won't countenance multiple inheritance at all, and C++
will botch it all by giving you a separate copy of the common
superclass's state for each protocol implementation (what are the
chances that everyone decided to use a virtual base class?) /and/
hideously breaking upwards delegation.

-- [mdw]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Deditor 0.2.2

2010-11-09 Thread TheSeeker
On Nov 9, 10:04 am, Kruptein  wrote:
> On Nov 8, 3:01 pm, Jean-Michel Pichavant 
> wrote:
>
>
>
>
>
>
>
>
>
> > TheSeeker wrote:
> > > On Nov 6, 7:06 am, Kruptein  wrote:
>
> > >> Hey,
>
> > >> I released version 0.2.2 of my pythonic text-editor  Deditor.
> > >> It adds the use of projects, a project is a set of files which you can
> > >> open all at once to make development much faster and easier.
>
> > >> For more information visit launchpad:http://launchpad.net/deditor
>
> > >> I also uploaded a video to introduce you to 
> > >> deditor:http://www.youtube.com/watch?v=hS8xBu-39VI
> > >> (note: youtube is still processing the file so you might have to wait
> > >> a bit to see it)
>
> > > Hi,
> > > I might have missed this, but it seems deditor requires Python above
> > > 2.5?
>
> > > It would be nice to mention the requirements on the home page
> > > somewhere.
>
> > > Thanks,
> > > Duane
>
> > I already point that on the last release. You should really just
> > consider writing the requirements (python & wx).
>
> > JM
>
> I'm going todo that right now! I alswyas forget it :p

Hi,

I was wondering if there was any reason deditor will not work under
Windows? I tried to run it and got the following (Python 2.6, wxPython
2.8):

Traceback (most recent call last):
  File "C:\junk\deditor-0.2.2\deditor.py", line 910, in 
deditor = DEDITOR(None, -1, "")
  File "C:\junk\deditor-0.2.2\deditor.py", line 101, in __init__
self.initialize()
  File "C:\junk\deditor-0.2.2\deditor.py", line 342, in initialize
self.menu.SetLabel(4,self.menu.GetLabel(4).strip("_")
+"\t"+"+".join(self.get
_base_config("keys", "ctab").split(",")))
  File "C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py",
line 1136
6, in GetLabel
return _core_.MenuBar_GetLabel(*args, **kwargs)
wx._core.PyAssertionError: C++ assertion "item" failed at ..\..\src
\common\menuc
mn.cpp(1125) in wxMenuBarBase::GetLabel(): wxMenuBar::GetLabel(): no
such item


Thanks,
Duane
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Silly newbie question - Caret character (^)

2010-11-09 Thread Mark Wooding
Philip Semanchuk  writes:

> What's funny is that I went looking for a printed copy of the C
> standard a few years back and the advice I got was that the cheapest
> route was to find a used copy of Schildt's "Annotated ANSI C Standard"
> and ignore the annotations. So it serves at least one useful purpose.

The book was much cheaper than a copy of the C standard from ANSI or ISO
even when it was new.  It was a common joke (HHOS) at the time that the
difference in price reflected the value of the annotations.

(It also has two errors in the actual text of the standard.  There's a
character missing in the syntax summary, and one page was omitted
entirely, replaced by a copy of the previous page: my copy came with a
corrected page ineptly glued in at the relevant place.)

-- [mdw]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: functions, list, default parameters

2010-11-09 Thread Mark Wooding
Lawrence D'Oliveiro  writes:

> In message , Robert Kern 
> wrote:
> > So examining LHS "selectors" is not sufficient for determining
> > immutability.
>
> Yes it is. All your attempts at counterexamples showed is that it is not 
> necessary, not that it is not sufficient.

You've got them the wrong way around.  A is sufficient for B if and only
if B is true whenever A is true; i.e., it is never the case that A is
true and B is false.  In this case, we also say that B is necessary for
A.

See also http://en.wikipedia.org/wiki/Necessary_and_sufficient_condition

-- [mdw]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why "flat is better than nested"?

2010-11-09 Thread John Posner

On 11/9/2010 3:44 PM, Gregory Ewing wrote:


I don’t get it.


I get it. Does that mean that I don't get it?


Yes. As Dr. Feynman said about quantum mechanics.

-John



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


Re: populating a doubly-subscripted array

2010-11-09 Thread Gregory Ewing

Mark Wooding wrote:


What [x] * n does is make a list, whose length is n, and all of whose
entries are precisely the value x.  If x itself is a list, then you get
an outer list all of whose entries are the /same/ inner list


A reasonably elegant way to fix this is to use list comprehensions
for all except the innermost list:

   ff = [[0.0]*5 for i in xrange(5)]

If you're computing heavily with arrays, you might also consider
using numpy arrays instead of lists.

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


Re: JavaScript vs Python

2010-11-09 Thread Stef Mientki
On 09-11-2010 10:25, Lawrence D'Oliveiro wrote:
> In message , Chris 
> Rebert wrote:
>
>> On Mon, Nov 8, 2010 at 10:52 PM, Lawrence D'Oliveiro
>>  wrote:
>>
>>> Because JavaScript is actually a decent language in its own right.
>> "The Good Parts" of it anyway.
> Python, too, has its good parts, you have to admit...
And there's a (or even more) Python to JS compilers,
I never heard of a JS to Python compiler.

cheers,
Stef
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Pyhton - Functional Programming - How intersect/difference two dict with dict/values? fast!

2010-11-09 Thread D'Arcy J.M. Cain
On Tue, 09 Nov 2010 15:55:16 -0500
Terry Reedy  wrote:
> To echo John Nagle's point, if you want non-masochist volunteers to read 
> your code, write something readable like:
> 
> dict1 = {'ab': [[1,2,3,'d3','d4',5], 12],
>   'ac': [[1,3,'78a','79b'], 54],
>   'ad': [[56,57,58,59], 34],
>   'ax': [[56,57,58,59], 34]}

I have been learning to like this form:

dict1 = dict(
  ab = [[1,2,3,'d3','d4',5], 12],
  ac = [[1,3,'78a','79b'], 54],
  ad = [[56,57,58,59], 34],
  ax = [[56,57,58,59], 34],
)

Of course, it only works when all the keys are strings.

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Pyhton - Functional Programming - How intersect/difference two dict with dict/values? fast!

2010-11-09 Thread Terry Reedy



On 11/9/2010 9:32 AM, macm wrote:



dict1 = {'ab':[[1,2,3,'d3','d4',5],12],'ac':[[1,3,'78a','79b'],
54],'ad': [[56,57,58,59],34], 'ax': [[56,57,58,59],34]}


To echo John Nagle's point, if you want non-masochist volunteers to read 
your code, write something readable like:


dict1 = {'ab': [[1,2,3,'d3','d4',5], 12],
 'ac': [[1,3,'78a','79b'], 54],
 'ad': [[56,57,58,59], 34],
 'ax': [[56,57,58,59], 34]}

--
Terry Jan Reedy

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


Re: Why "flat is better than nested"?

2010-11-09 Thread Gregory Ewing

Lawrence D'Oliveiro wrote:

In message
, rustom 
wrote:



If you take zen seriously you dont get it
If you dont take zen seriously you dont get it
That -- seriously -- is zen


I don’t get it.


I get it. Does that mean that I don't get it?

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


Re: Learning Pyhton - Functional Programming - How intersect/difference two dict with dict/values? fast!

2010-11-09 Thread John Nagle

On 11/9/2010 9:32 AM, macm wrote:

Hi Folks,

dict1 = {'ab':[[1,2,3,'d3','d4',5],12],'ac':[[1,3,'78a','79b'],
54],'ad': [[56,57,58,59],34], 'ax': [[56,57,58,59],34]}
dict2 = {'ab':[[22,2,'a0','42s','c4','d3'],12],'ab':[[2,4,50,42,'c4'],
12],'ac':[[1,3,'79b',45,65,'er4'],54],'ae': [[56,57,58,59],34],'ax':
[[9],34]}
dict3 = {'ac':[[1,3,67,'gf'],12],'at':[[2,4,50,42,'c4'],12],'as':
[[1,3,'79b',45,65,'er4'],54],'ae': [[56,57,58,59],34]}
intersect = filter(dict1.has_key, dict2.keys())
intersect
result:
['ax', 'ac', 'ab']


When you've spent a year maintaining and fixing code written
by others, come back and we'll talk.

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


Re: An easier way to do this? (spoiler if you're using pyschools for fun)

2010-11-09 Thread Terry Reedy

On 11/9/2010 2:00 PM, Matty Sarro wrote:


I'm working on one of the puzzles on pyschools.com
, and am trying to figure out if I can make my
solution a bit more elegant.


Definitely


def getSumOfLastDigit(numList):
 sumOfDigits=0
 for i in range(0, len(numList)):
 num=str(numList.pop())


This is an awkward way to iterate through a list ;-)


 sumOfDigits+=int(num[-1:])
 return sumOfDigits



Write a function: getSumOfLastDigit(numList) that takes in a list of
positive numbers and returns the sum of all the last digit in the list.

*Examples*
>>>  getSumOfLastDigit([12,  23,  34])
9
>>>  getSumOfLastDigit([2,  3,  4])
9
>>>  getSumOfLastDigit([1,  23,  456])
10


# Straightforward version of what you did

def getSumOfLastDigit(numList):
sumOfDigits=0
for i in numList:
sumOfDigits+=int(str(i)[-1:])
return sumOfDigits

print(getSumOfLastDigit([12, 23, 34]),
  getSumOfLastDigit([2, 3, 4]),
  getSumOfLastDigit([1, 23, 456]) )
# 9 9 10

# Use generator expression with built-in sum function

def getSumOfLastDigit(numList):
return sum(int(str(i)[-1:]) for i in numList)

print(getSumOfLastDigit([12, 23, 34]),
  getSumOfLastDigit([2, 3, 4]),
  getSumOfLastDigit([1, 23, 456]) )
# 9 9 10

--
Terry Jan Reedy

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


Re: An easier way to do this? (spoiler if you're using pyschools for fun)

2010-11-09 Thread Peter Otten
Matty Sarro wrote:

> Hey everyone,
> I'm working on one of the puzzles on pyschools.com, and am trying to
> figure out if I can make my solution a bit more elegant.
> 
> def getSumOfLastDigit(numList):
> sumOfDigits=0
> for i in range(0, len(numList)):
> num=str(numList.pop())
> sumOfDigits+=int(num[-1:])
> return sumOfDigits
> 
> Below is the problem. Basically you take the last digit of each number in
> the list, and add them together.
> 
> Write a function: getSumOfLastDigit(numList) that takes in a list of
> positive numbers and returns the sum of all the last digit in the list.
> 
> *Examples*
> 
>>>> getSumOfLastDigit([12, 23, 34])
>9
>>>> getSumOfLastDigit([2, 3, 4])
>9
>>>> getSumOfLastDigit([1, 23, 456])
>10

Loop over a list directly:

for n in numlist:
   # ...

Use the modulo (%) operator to find the last digit:

last_digit = n % 10

There is a built-in sum() function:

sum([1,2,3]) # 6

There is an inlined form of the for-loop called "generator expression"

sum(i*i for i in [1,2,3]) # 14

Putting it all together:

>>> def gsold(numbers):
... return sum(i%10 for i in numbers)
...
>>> gsold([12,23,34])
9
>>> gsold([2,3,4])
9
>>> gsold([1,23,456])
10

Peter

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


Re: An easier way to do this? (spoiler if you're using pyschools for fun)

2010-11-09 Thread Chris Rebert
On Tue, Nov 9, 2010 at 11:00 AM, Matty Sarro  wrote:
> Hey everyone,
> I'm working on one of the puzzles on pyschools.com, and am trying to figure
> out if I can make my solution a bit more elegant.
>
> def getSumOfLastDigit(numList):
>     sumOfDigits=0
>     for i in range(0, len(numList)):
>         num=str(numList.pop())
Just loop over the list directly:
for num in numList:
num = str(num)
>         sumOfDigits+=int(num[-1:])
No need for the colon:
sumOfDigits+= int(num[-1])
>     return sumOfDigits

And now for the much simpler math-based solution:

def getSumOfLastDigit(numList):
return sum(num%10 for num in numList)

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


An easier way to do this? (spoiler if you're using pyschools for fun)

2010-11-09 Thread Matty Sarro
Hey everyone,
I'm working on one of the puzzles on pyschools.com, and am trying to figure
out if I can make my solution a bit more elegant.

def getSumOfLastDigit(numList):
sumOfDigits=0
for i in range(0, len(numList)):
num=str(numList.pop())
sumOfDigits+=int(num[-1:])
return sumOfDigits

Below is the problem. Basically you take the last digit of each number in
the list, and add them together.

Write a function: getSumOfLastDigit(numList) that takes in a list of
positive numbers and returns the sum of all the last digit in the list.

*Examples*

   >>> getSumOfLastDigit([12, 23, 34])
   9
   >>> getSumOfLastDigit([2, 3, 4])
   9
   >>> getSumOfLastDigit([1, 23, 456])
   10
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary of lists strange behaviour

2010-11-09 Thread Terry Reedy

On 11/9/2010 12:19 PM, Ciccio wrote:

Il 09/11/2010 16:47, Terry Reedy ha scritto:

On 11/9/2010 9:14 AM, Ciccio wrote:

Hi all,

hope you can help me understanding why the following happens:

In [213]: g = {'a': ['a1','a2'], 'b':['b1','b2']}
In [214]: rg = dict.fromkeys(g.keys(),[])


If you rewrite this as

bl = []
rg = dict.fromkeys(g.keys(),bl)

is the answer any more obvious?


It isn't since I erroneously assumed that a clone of the object would be
made in both cases.


I can see how you might think that, especially if you have experience 
with other languages where that would be usual. In Python, the general 
policy is to not copy objects unless explicitly requested. None, False, 
and True cannot be copied. There is essentially never a reason to copy a 
number or string or tuple.


I believe dict.fromkeys is more usually given None or 0 or '' as value 
initializer. List *is* useful as an initializer for 
collecitons.defaultdicts.


--
Terry Jan Reedy

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


Re: Learning Pyhton - Functional Programming - How intersect/difference two dict with dict/values? fast!

2010-11-09 Thread Peter Otten
macm wrote:

> Hi Folks,
> 
> dict1 = {'ab':[[1,2,3,'d3','d4',5],12],'ac':[[1,3,'78a','79b'],
> 54],'ad': [[56,57,58,59],34], 'ax': [[56,57,58,59],34]}
> dict2 = {'ab':[[22,2,'a0','42s','c4','d3'],12],'ab':[[2,4,50,42,'c4'],
> 12],'ac':[[1,3,'79b',45,65,'er4'],54],'ae': [[56,57,58,59],34],'ax':
> [[9],34]}
> dict3 = {'ac':[[1,3,67,'gf'],12],'at':[[2,4,50,42,'c4'],12],'as':
> [[1,3,'79b',45,65,'er4'],54],'ae': [[56,57,58,59],34]}
> intersect = filter(dict1.has_key, dict2.keys())
> intersect
> result:
> ['ax', 'ac', 'ab']
> 
> expect result dict1 intersection with dict2
> {'ac':[1,3,'79b'], 'ab':[2,'d3']} # look last key/value 'ax' (dict1,
> dict2) even intersec a key but not values from list so not valid
> 
> and difference from dict3
> dict3 = {'ac':[[1,3,67,'gf'],12],'at':[[2,4,50,42,'c4'],12],'as':
> [[1,3,'79b',45,65,'er4'],54],'ae': [[56,57,58,59],34]}
> 
> result from (intersect - dict3)
> {'ac':['79b'], 'ab':[2,'d3']}
> 
> Thanks in advance!
> 
> Before someone blame me.
> 
> Yes I am trying learn python Functional Programming! ; )

>>> dict((k, v) for k, v in ((k, [a for a in v if a in w]) for k, v, w in 
((k, v[0], set(dict2[k][0])) for k, v in dict1.iteritems() if k in dict2)) 
if v)
{'ac': [1, 3, '79b'], 'ab': [2]}

Replacing the genexps with map/filter/lambda is left as an exercise.

> Before someone blame me.

I'm trying to set new standards in readability ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if a module exists?

2010-11-09 Thread Jon Dufresne
On Mon, Nov 8, 2010 at 11:35 PM, Lawrence D'Oliveiro
 wrote:
> In message , Roy Smith wrote:
>
>> On the other hand, if your module's bug is that it in turn imports some
>> other module, which doesn't exist, you'll also get an ImportError.
>
> Does it really matter? Either way, the module is unusable.

In my program it matters.

If the module exists but is buggy, then I want to be notified
immediately to fix it. However if the module does not exist in an
extension module (keyword being extension) then the extensions doesn't
add behavior to that part of the program.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if a module exists?

2010-11-09 Thread Jon Dufresne
On Tue, Nov 9, 2010 at 4:30 AM, Roy Smith  wrote:
> In article ,
>  Lawrence D'Oliveiro  wrote:
>
>> In message , Roy Smith wrote:
>>
>> > On the other hand, if your module's bug is that it in turn imports some
>> > other module, which doesn't exist, you'll also get an ImportError.
>>
>> Does it really matter? Either way, the module is unusable.
>
> If I understand correctly, he's trying to differentiate between:
>
> 1) The module is unusable because it's not installed
>
> 2) The module is unusable because it has a bug in it.
>


Yes. Case 1 is an acceptable case. In case 1, if the extension module
(extension as in extension to my core program) does not have magic.py
then the extension adds no behavior in the magic1 portion of the
program. However, if the extension does have magic.py but it is buggy
(case 2), I want my program to fail. Currently I am doing this using
the traceback code suggested in an earlier post.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Silly newbie question - Caret character (^)

2010-11-09 Thread Terry Reedy

On 11/9/2010 2:00 AM, Seebs wrote:


Yes, Herb Schildt:
http://www.seebs.net/c/c_tcn4e.html


I've been wondering why C programmers keep writing code susceptible to 
buffer overruns ;=).


Your two 'nitpicks' about fflush have both come up on this list as real 
issues causing people problems. So I agree that it needs to be explained 
properly and completely as you suggest.

--
Terry Jan Reedy

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


Learning Pyhton - Functional Programming - How intersect/difference two dict with dict/values? fast!

2010-11-09 Thread macm
Hi Folks,

dict1 = {'ab':[[1,2,3,'d3','d4',5],12],'ac':[[1,3,'78a','79b'],
54],'ad': [[56,57,58,59],34], 'ax': [[56,57,58,59],34]}
dict2 = {'ab':[[22,2,'a0','42s','c4','d3'],12],'ab':[[2,4,50,42,'c4'],
12],'ac':[[1,3,'79b',45,65,'er4'],54],'ae': [[56,57,58,59],34],'ax':
[[9],34]}
dict3 = {'ac':[[1,3,67,'gf'],12],'at':[[2,4,50,42,'c4'],12],'as':
[[1,3,'79b',45,65,'er4'],54],'ae': [[56,57,58,59],34]}
intersect = filter(dict1.has_key, dict2.keys())
intersect
result:
['ax', 'ac', 'ab']

expect result dict1 intersection with dict2
{'ac':[1,3,'79b'], 'ab':[2,'d3']} # look last key/value 'ax' (dict1,
dict2) even intersec a key but not values from list so not valid

and difference from dict3
dict3 = {'ac':[[1,3,67,'gf'],12],'at':[[2,4,50,42,'c4'],12],'as':
[[1,3,'79b',45,65,'er4'],54],'ae': [[56,57,58,59],34]}

result from (intersect - dict3)
{'ac':['79b'], 'ab':[2,'d3']}

Thanks in advance!

Before someone blame me.

Yes I am trying learn python Functional Programming! ; )

Best Regards

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


Re: A way to get setup.py to create links instead of copy

2010-11-09 Thread Steve Holden
On 11/9/2010 4:18 AM, Geoff Bache wrote:
> Hi all,
> 
> One of the things I've always loved about Python (having come from
> compiled languages) was the lack of an extra step between changing my
> code and running it.
> 
> On my current project, however, I find that I have to install my
> Python code with setup.py before it will run. Being used to not having
> this step, I easily forget to run setup.py install before they will
> run, and then spend time wondering why my changes didn't work.
> 
> So I went into the target directory and replaced the copies with
> symbolic links back to the original code. This felt like a hack but
> does mean I don't have to install the whole time any more.
> 
> I wonder if there is some standard way to deal with this situation?
> 
Yes, there is. It involves (to a first approximation) understanding the
role of sys.path, and its relationship with the PYTHONPATH environment
variable. In brief, this tells the interpreter where to look for modules
when it is importing.

Installation with setup.py is normally reserved for a fairly permanent
insertion of the code into your Python distribution, which might have
added it for all users. If this is an issue you may want to undo the
installation manually by removing its additions to your Python's
Lib/site-packages directory.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon 2011 Atlanta March 9-17   http://us.pycon.org/
See Python Video!   http://python.mirocommunity.org/
Holden Web LLC http://www.holdenweb.com/

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


Re: Dictionary of lists strange behaviour

2010-11-09 Thread Ciccio

Thank you all, this was timely and helpful.
francesco
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary of lists strange behaviour

2010-11-09 Thread Ciccio

Il 09/11/2010 16:47, Terry Reedy ha scritto:

On 11/9/2010 9:14 AM, Ciccio wrote:

Hi all,

hope you can help me understanding why the following happens:

In [213]: g = {'a': ['a1','a2'], 'b':['b1','b2']}
In [214]: rg = dict.fromkeys(g.keys(),[])


If you rewrite this as

bl = []
rg = dict.fromkeys(g.keys(),bl)

is the answer any more obvious?


It isn't since I erroneously assumed that a clone of the object would be 
made in both cases.


Thanks for your help
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help Documenting Python Syntax

2010-11-09 Thread Terry Reedy

On 11/9/2010 10:26 AM, RJB wrote:

I have been trying to redevelop a syntax page for Python at
  http://cse.csusb.edu/dick/samples/python.syntax.html


Page does not load correctly; had to hit refresh to get entire page.
It should specify that this is the syntax for Python 2.5. To me "the 
Python language" is 3.2.



I would appreciate and encouragement or corrections -- because I know
there is at least one gross error in there.


--
Terry Jan Reedy

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


Re: udp sockets with python

2010-11-09 Thread Jean-Paul Calderone
On Nov 9, 5:20 am, Mag Gam  wrote:
> Hello,
>
> When measuring round trip time for the UDP echo client/server the C
> version is much faster. I was wondering if there is anything I can do
> to speed up.
>
> My current code for client looks like this
>
> sock=socket(AF_INET,SOCK_DGRAM)
> for x in range (1000):
>   sock.sendto("foo",(server,port))
>   a=sock.recv(256)
>
> sock.close()
>
> The server code looks like this:
> UDPsock=socket(AF_INET,SOCK_DGRAM)
> UDPSock.bind(addr)
> while 1:
>   m,c=UDPsock,recvfrom(1024)
>   UDPsock.sendto('bar',c)
>
> UDPsock.close()
>
> I am measuring the round trip time using tcpdump. The C version is
> giving me around 80 microseconds (average) and the python is giving me
> close to 300 microseconds (average).

Try replacing the hostname in your send calls with an IP address.  If
you're not passing an IP address here, then the Python version has to
do a name lookup for each send, I bet your C version is not.

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


Re: Help Documenting Python Syntax

2010-11-09 Thread Grant Edwards
On 2010-11-09, Terry Reedy  wrote:
> On 11/9/2010 10:26 AM, RJB wrote:
>> I have been trying to redevelop a syntax page for Python at
>>   http://cse.csusb.edu/dick/samples/python.syntax.html
>
> Page does not load correctly; had to hit refresh to get entire page.
> It should specify that this is the syntax for Python 2.5. To me "the 
> Python language" is 3.2.

Nope.  I just checked, and it's 2.6.5:

  $ python
  Python 2.6.5 (release26-maint, Aug  9 2010, 11:06:44) 

;)

My question is why bother with 2.5?

I would think the logical choices would be 3.2 or 2.7 (or maybe 2.6).

-- 
Grant Edwards   grant.b.edwardsYow! I have a TINY BOWL in
  at   my HEAD
  gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Deditor 0.2.2

2010-11-09 Thread Kruptein
On Nov 8, 3:01 pm, Jean-Michel Pichavant 
wrote:
> TheSeeker wrote:
> > On Nov 6, 7:06 am, Kruptein  wrote:
>
> >> Hey,
>
> >> I released version 0.2.2 of my pythonic text-editor  Deditor.
> >> It adds the use of projects, a project is a set of files which you can
> >> open all at once to make development much faster and easier.
>
> >> For more information visit launchpad:http://launchpad.net/deditor
>
> >> I also uploaded a video to introduce you to 
> >> deditor:http://www.youtube.com/watch?v=hS8xBu-39VI
> >> (note: youtube is still processing the file so you might have to wait
> >> a bit to see it)
>
> > Hi,
> > I might have missed this, but it seems deditor requires Python above
> > 2.5?
>
> > It would be nice to mention the requirements on the home page
> > somewhere.
>
> > Thanks,
> > Duane
>
> I already point that on the last release. You should really just
> consider writing the requirements (python & wx).
>
> JM

I'm going todo that right now! I alswyas forget it :p
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Commercial or Famous Applicattions.?

2010-11-09 Thread Grant Edwards
On 2010-11-09, Jorge Biquez  wrote:

> Can you mention applications/systems/solutions made with Python that 
> are well known and used by public in general? ANd that maybe we do 
> not know they are done with Python?

I'm not sure how much the "public in general" knows about it, but one
I ran across recently is OpenERP:

  http://www.openerp.com/

It's a complete CRM/purchasing/HR/Accouting/Inventory/etc. system for
businesses.

Other programs I've used that I noticed were written in Python:

 Freevo (PVR/DVR HTPC media center)

 bittorrent (the original apps)

 RedHat's installer and some admin utils.

 Gentoos "emerge" build system.

 meld (source code diff/merge tool)

 skencil (vector drafting program)

 bitpim (cellphone data synch app)

 PyNeighborhood (network neighborhood browser)
 
I'm sure there are dozens more that I've used and never realized they
were written in Python.

Last time I checked IBM/Lenovo computers all came with Python
installed, since some of the pre-installed admin/maintenance stuff is
written in Python.

-- 
Grant Edwards   grant.b.edwardsYow! Are we live or on
  at   tape?
  gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary of lists strange behaviour

2010-11-09 Thread Terry Reedy

On 11/9/2010 9:14 AM, Ciccio wrote:

Hi all,

hope you can help me understanding why the following happens:

In [213]: g = {'a': ['a1','a2'], 'b':['b1','b2']}
In [214]: rg = dict.fromkeys(g.keys(),[])


If you rewrite this as

bl = []
rg = dict.fromkeys(g.keys(),bl)

is the answer any more obvious?



In [215]: rg
Out[215]: {'a': [], 'b': []}
In [216]: rg['a'].append('x')
In [217]: rg
Out[217]: {'a': ['x'], 'b': ['x']}

What I meant was appending 'x' to the list pointed by the key 'a' in the
dictionary 'rg'. Why rg['b'] is written too?



--
Terry Jan Reedy

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


Help Documenting Python Syntax

2010-11-09 Thread RJB
I have been trying to redevelop a syntax page for Python at
 http://cse.csusb.edu/dick/samples/python.syntax.html

I would appreciate and encouragement or corrections -- because I know
there is at least one gross error in there.

By the way, this is part of a suite of language definitions... going
back to the 1960's

RJBotting
Who was PAR in the early 1980's
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Silly newbie question - Caret character (^)

2010-11-09 Thread Philip Semanchuk

On Nov 9, 2010, at 1:04 AM, Lawrence D'Oliveiro wrote:

> In message , Seebs wrote:
> 
>> On 2010-11-09, Lawrence D'Oliveiro 
>> wrote:
>> 
>>> In message , Dennis
>>> Lee Bieber wrote:
 
 Have you ever looked at the reference manual for Ada?
>> 
>>> Or even worse, the annotated reference. I thought annotations were
>>> supposed to clarify things; in this case they seemed to have the opposite
>>> effect...
>> 
>> Clearly, you've never seen Schildt's infamous "Annotated ANSI C Standard".
> 
> There absolutely no chance (or at least no way I can imagine) that anyone 
> could annotate a concise language like C up to the level of turgidity of the 
> Ada spec.
> 
> Hang on, is this Herb Schildt? I bought a couple of his books, back when I 
> was trying to get to grips with C++ (I have the edition of “C++ The Complete 
> Reference” which proudly proclaims it “Covers the New International Standard 
> for C+”). Not as useful as I thought they would be; I ended up referring to 
> the libstdc++ sources to clarify things.

What's funny is that I went looking for a printed copy of the C standard a few 
years back and the advice I got was that the cheapest route was to find a used 
copy of Schildt's "Annotated ANSI C Standard" and ignore the annotations. So it 
serves at least one useful purpose.

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


Re: Dictionary of lists strange behaviour

2010-11-09 Thread Jean-Michel Pichavant

Ciccio wrote:

Hi all,

hope you can help me understanding why the following happens:

In [213]: g = {'a': ['a1','a2'], 'b':['b1','b2']}
In [214]: rg = dict.fromkeys(g.keys(),[])
In [215]: rg
Out[215]: {'a': [], 'b': []}
In [216]: rg['a'].append('x')
In [217]: rg
Out[217]: {'a': ['x'], 'b': ['x']}

What I meant was appending 'x' to the list pointed by the key 'a' in 
the dictionary 'rg'. Why rg['b'] is written too?


Thanks.


rg = dict.fromkeys(g.keys(),[])

you are intialising the content with the same object [].

write instead

for key in g:
   rg[key] = [] # python create a new list everytime it hits this line

For the same reason you never assign an empty list to default parameters 
value:


In [37]: def a(p=[]):
  : return p
  :

In [38]: a1 = a()

In [39]: a2 = a()

In [40]: id(a1) ; id(a2)
Out[40]: 161119884
Out[40]: 161119884

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


Re: Commercial or Famous Applicattions.?

2010-11-09 Thread Kevin Walzer

On 11/8/10 7:18 PM, Jorge Biquez wrote:

Hello all.

Newbie question. Sorry.

Can you mention applications/systems/solutions made with Python that are
well known and used by public in general? ANd that maybe we do not know
they are done with Python?


There are several on the Mac:

Checkout, a POS program:
http://checkoutapp.com/

EagleFiler, a file organizer:
http://c-command.com/eaglefiler/

Phynchronicity, a GUI for Fink package manager:
 http://www.codebykevin.com/phynchronicity.html

QuickWho, a whois search tool:
http://www.codebykevin.com/quickwho.html

I'm also sure there are others that I'm not aware of.

--Kevin


--
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
--
http://mail.python.org/mailman/listinfo/python-list


Free E-Books collection

2010-11-09 Thread naveed ahmed
Freeit http://freeit11.blogspot.comis the world's leading online
source of ebooks, with a vast range of

ebooks from academic,
Popular and professional publishers.

Freeit http://freeit11.blogspot.com eBook communicates my vision of
exploring the whole universe to you.

What if you
had a plausible method (based on today's science and technology)
freeit large selection of eBooks. New eBook releases and bestsellers
in
over 40 categories including science fiction, romance, mystery,
for more e-books visit Freeit
-- 
http://mail.python.org/mailman/listinfo/python-list


Dictionary of lists strange behaviour

2010-11-09 Thread Ciccio

Hi all,

hope you can help me understanding why the following happens:

In [213]: g = {'a': ['a1','a2'], 'b':['b1','b2']}
In [214]: rg = dict.fromkeys(g.keys(),[])
In [215]: rg
Out[215]: {'a': [], 'b': []}
In [216]: rg['a'].append('x')
In [217]: rg
Out[217]: {'a': ['x'], 'b': ['x']}

What I meant was appending 'x' to the list pointed by the key 'a' in the 
dictionary 'rg'. Why rg['b'] is written too?


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


Re: Dictionary of lists strange behaviour

2010-11-09 Thread Matteo Landi
On Tue, Nov 9, 2010 at 3:14 PM, Ciccio  wrote:
> Hi all,
>
> hope you can help me understanding why the following happens:
>
> In [213]: g = {'a': ['a1','a2'], 'b':['b1','b2']}
> In [214]: rg = dict.fromkeys(g.keys(),[])

The argument you pass which is used to fill the values of the new
dict, is created once; this means that the empty list is shared
between all the keys of the dict.
I think you need to create the new dict  by hand.

Regards,
Matteo

> In [215]: rg
> Out[215]: {'a': [], 'b': []}
> In [216]: rg['a'].append('x')
> In [217]: rg
> Out[217]: {'a': ['x'], 'b': ['x']}
>
> What I meant was appending 'x' to the list pointed by the key 'a' in the
> dictionary 'rg'. Why rg['b'] is written too?
>
> Thanks.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Matteo Landi
http://www.matteolandi.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cross compiling (i386 from amd64) with distutils

2010-11-09 Thread bobicanprogram
On Nov 7, 7:19 pm, Jason  wrote:
> My situation is this: I have a Diamond Systems single-board computer
> with a
> matching GPIO board. DS have a library for controlling the GPIO
> board... but
> it's a static library (libdscud-6.02.a) with an accompanying header
> (dscud.h).
> I'd like to create a Python extension to use the device.
>
> The architecture of the SBC is 486, and it runs Debian Squeeze/Grip.
> While it
> is possible to develop on it directly, I'd rather use my desktop
> machine
> (Debian Squeeze, amd64).
>
> If I write a simple C program to control the device, I'd include the
> header
> file and cross-compile it like so:
>
> gcc -m32 -march=i386 -lpthread -I/usr/local/dscud-6.02 -o dio
> dio.c \
> /usr/local/dscud-6.02/libdscud-6.02.a
>
> To get myself started with the Python extension, I've basically taken
> the
> "noddy" demo[1] and thrown in a function call from the DSC library
> just to see
> if I can get something to build.
>
> My distutils setup.py looks like:
>
> 
> from distutils.core import setup, Extension
>
> module1 = Extension('noddy',
> sources = ['src/noddy.c'],
> libraries = ['pthread'],
> include_dirs = ['/usr/local/dscud-6.02'],
> extra_objects = ['/usr/local/dscud-6.02/libdscud-6.02.a'],
> extra_compile_args = ['-m32', '-march=i386'])
>
> setup(name = 'Noddy', version = '1.0', description = 'This is a demo
> package',
>   ext_modules = [module1])
> 
>
> This works fine on the target machine with "python setup.py build",
> but when I
> try it on my desktop machine, I get:
>
> 
> $ python setup.py build
> running build
> running build_ext
> building 'noddy' extension
> creating build
> creating build/temp.linux-x86_64-2.6
> creating build/temp.linux-x86_64-2.6/src
> gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall
> -Wstrict-prototypes -fPIC -I/usr/local/dscud-6.02 -I/usr/include/
> python2.6 -c
> src/noddy.c -o build/temp.linux-x86_64-2.6/src/noddy.o -m32 -
> march=i386
> In file included from /usr/include/python2.6/Python.h:58,
>  from src/noddy.c:1:
> /usr/include/python2.6/pyport.h:694:2: error: #error "LONG_BIT
> definition
> appears wrong for platform (bad gcc/glibc config?)."
> error: command 'gcc' failed with exit status 1
>
> 
>
> So is it possible to get distutils to cross compile something like
> this, and
> if so, what am I missing? Or am I using the wrong tool for the job?
>
> Target python ver. is 2.6. GCC is 4.4.5.
>
> Cheers,
> Jason
>
> [1]http://docs.python.org/extending/newtypes.html


Cross compilation might be one solution to Python access.   The SIMPL
toolkit (http://www.icanprogram.com/simpl; 
http://www.icanprogram.com/06py/lesson1/lesson1.html)
might be easier.   If you ultimately want to communicate from a 64bit
to a 32bit system,  you'll probably want to use a text based tokenized
messaging strategy as opposed to the binary one in these examples.

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


Re: Commercial or Famous Applicattions.?

2010-11-09 Thread Martin Gregorie
On Tue, 09 Nov 2010 00:47:08 +, brf256 wrote:

> Mailman is of course.
>
...and don't forget getmail, a better behaved replacement for fetchmail.


-- 
martin@   | Martin Gregorie
gregorie. | Essex, UK
org   |
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best exercises for beginers to learn?

2010-11-09 Thread Matty Sarro
I agree completely with Seebs, however I will mention that until you find a
project that tickles your fancy there are some good places to find
exercises.
Pyschools: http://www.pyschools.com
Project Euler: http://projecteuler.net/
You can also check out: http://learnpythonthehardway.org/index
The exercises are pretty good.

On Tue, Nov 9, 2010 at 3:27 AM, Seebs  wrote:

> On 2010-11-08, brf...@gmail.com  wrote:
> > I was wondering if there are any good exercises that you
> > would recommend learning?
>
> Yes.
>
> *Write something you want to use.*
>
> Nothing will teach you programming as fast as programming stuff you care
> about for the joy of having it.  Exercises that you don't care about in
> their own right will not catch you the same way.
>
> If you write something you want to have, you will not stop when it
> happens to work, but will keep tweaking it and improving it so it does
> what you want.  That will teach you more than *any* prefab exercise that
> has no particular significance to you.
>
> -s
> --
> Copyright 2010, all wrongs reversed.  Peter Seebach /
> usenet-nos...@seebs.net
> http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
> http://en.wikipedia.org/wiki/Fair_Game_(Scientology)<--
>  get educated!
> I am not speaking for my employer, although they do rent some of my
> opinions.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic/idiomatic?

2010-11-09 Thread Jean-Michel Pichavant

Seebs wrote:

I have an existing hunk of Makefile code:
CPPFLAGS = "$(filter -D* -I* -i* -U*,$(TARGET_CFLAGS))"
For those not familiar with GNU makeisms, this means "assemble a string
which consists of all the words in $(TARGET_CFLAGS) which start with one
of -D, -I, -i, or -U".  So if you give it
foo -Ibar baz
it'll say
-Ibar

I have a similar situation in a Python context, and I am wondering
whether this is an idiomatic spelling:

' '.join([x for x in target_cflags.split() if re.match('^-[DIiU]', x)])

This appears to do the same thing, but is it an idiomatic use of list
comprehensions, or should I be breaking it out into more bits?

You will note that of course, I have carefully made it a one-liner so I
don't have to worry about indentation*.

-s
[*] Kidding, I just thought this seemed like a pretty clear expression.
  

One pythonic way to do it, is to use an option parser.

optparse (or argparse if python > 2.7)

JM

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


RE: { '0':'c->c->a' ,'1':'a->b->a' .........}

2010-11-09 Thread Sells, Fred
Since your keys are not unique, I would think that you would want a list
of values for the object corresponding to each key.  Something like

Mydict = {}

Mydict.setdefault(mykey, []).append(avalue)

-Original Message-
From: python-list-bounces+frsells=adventistcare@python.org
[mailto:python-list-bounces+frsells=adventistcare@python.org] On
Behalf Of Peter Otten
Sent: Sunday, November 07, 2010 4:01 PM
To: python-list@python.org
Subject: Re: { '0':'c->c->a' ,'1':'a->b->a' .}

chris wrote:
> have anybody a hint , how i get a dict from non unique id's and their
> different related values.
> 
> Thanks for advance
> Chris
> 
> ###random data #
> a=range(10)*3
> def seqelem():
> i=random.randint(0,2)
> elem=['a','b','c'][i]
> return elem
> 
> s=[seqelem() for t in  range(30)]
> print zip(a,s)
> 
> ## favored result:
> { '0':'c->c->a' ,'1':'a->b->a' .}

>>> import random
>>> from collections import defaultdict
>>> a = range(10)*3
>>> s = [random.choice("abc") for _ in a]
>>> d = defaultdict(list)
>>> for k, v in zip(a, s):
... d[k].append(v)
...
>>> d
defaultdict(, {0: ['b', 'a', 'a'], 1: ['c', 'a', 'c'], 2:
['c', 
'c', 'c'], 3: ['c', 'a', 'a'], 4: ['b', 'c', 'a'], 5: ['b', 'c', 'c'],
6: 
['c', 'a', 'b'], 7: ['b', 'b', 'a'], 8: ['a', 'c', 'c'], 9: ['b', 'a', 
'b']})
>>> dict((k, "->".join(v)) for k, v in d.iteritems())
{0: 'b->a->a', 1: 'c->a->c', 2: 'c->c->c', 3: 'c->a->a', 4: 'b->c->a',
5: 
'b->c->c', 6: 'c->a->b', 7: 'b->b->a', 8: 'a->c->c', 9: 'b->a->b'}

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

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


Re: Compare source code

2010-11-09 Thread Neil Cerutti
On 2010-11-07, Ethan Furman  wrote:
> Lawrence D'Oliveiro wrote:
>> In message , Tim Harig wrote:
>>> I personally prefer tabs as it lets *me* decide how far the
>>> apparent indentations are in the code.
>> 
>> But they don???t. Other people can have different settings,
>> and they will see different indentations for your code
>
> That's exactly the point -- each person can decide what level
> of indentation they prefer to look at.

That ideal works only if you are disciplined to never mix tabs
and spaces. "Wrapped" lines can become ugly when tabstop is
changed.

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


Re: How to test if a module exists?

2010-11-09 Thread Roy Smith
In article ,
 Lawrence D'Oliveiro  wrote:

> In message , Roy Smith wrote:
> 
> > On the other hand, if your module's bug is that it in turn imports some
> > other module, which doesn't exist, you'll also get an ImportError.
> 
> Does it really matter? Either way, the module is unusable.

If I understand correctly, he's trying to differentiate between:

1) The module is unusable because it's not installed

2) The module is unusable because it has a bug in it.

The later case implies he needs to find and fix the bug.
-- 
http://mail.python.org/mailman/listinfo/python-list


udp sockets with python

2010-11-09 Thread Mag Gam
Hello,

When measuring round trip time for the UDP echo client/server the C
version is much faster. I was wondering if there is anything I can do
to speed up.

My current code for client looks like this

sock=socket(AF_INET,SOCK_DGRAM)
for x in range (1000):
  sock.sendto("foo",(server,port))
  a=sock.recv(256)

sock.close()


The server code looks like this:
UDPsock=socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)
while 1:
  m,c=UDPsock,recvfrom(1024)
  UDPsock.sendto('bar',c)

UDPsock.close()


I am measuring the round trip time using tcpdump. The C version is
giving me around 80 microseconds (average) and the python is giving me
close to 300 microseconds (average).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary of lists strange behaviour

2010-11-09 Thread Dave Angel



On 2:59 PM, Ciccio wrote:

Hi all,

hope you can help me understanding why the following happens:

In [213]: g = {'a': ['a1','a2'], 'b':['b1','b2']}
In [214]: rg = dict.fromkeys(g.keys(),[])
In [215]: rg
Out[215]: {'a': [], 'b': []}
In [216]: rg['a'].append('x')
In [217]: rg
Out[217]: {'a': ['x'], 'b': ['x']}

What I meant was appending 'x' to the list pointed by the key 'a' in 
the dictionary 'rg'. Why rg['b'] is written too?


Thanks.

The second argument to the fromkeys() method is an empty list object.  
So that object is the value for *both* the new dictionary items.  It 
does not make a new object each time, it uses the same one.


You can check this for yourself, by doing
   id(rg["a"])  and  id(rg["b"])

I'd do something like :

rg = {}
for key in g.keys():
  rg[key] = []

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


Re: How to test if a module exists?

2010-11-09 Thread Jean-Michel Pichavant

Jon Dufresne wrote:

On Sat, Nov 6, 2010 at 1:52 PM, Roy Smith  wrote:
  

import sys
try:
   import xx
except ImportError:
   tb = sys.exc_traceback
   while tb:
   print tb
   tb = tb.tb_next




I went ahead and implemented this and it now works. I even uncovered a
bug I wasn't previously seeing because now the program was failing
early! :)

I hope there isn't a hidden naivete in using this pattern.

Thanks,
Jon
  

try:
  :import xx
  : except ImportError:
  :tb = sys.exc_traceback
  :while tb:
  :print tb
  :tb = tb.tb_next
  :



I don't see how it solves your problem. It does not test if a module 
exists, nor does it handles missing or flawed modules differently.


JM

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


Re: List index out of range, but list has enough elements

2010-11-09 Thread Stefan Behnel

[rearranged the responses in the right order]

Costin Gamenț, 09.11.2010 11:44:

On Tue, Nov 9, 2010 at 3:21 PM, Costin Gamenț wrote:

On Tue, Nov 9, 2010 at 11:33 AM, Stefan Behnel wrote:

Costin Gamenț, 09.11.2010 10:24:

Hi, I am trying to read a string as csv, but I encountered an odd
problem. Here's my code:

csvfile = csv.reader(datastr.split('\n'), delimiter=';')
r = ''
for i in csvfile:
for j in i:
print j
print i[0]

the "print j" statement works, but "print i[0]" returns "IndexError:
list index out of range". Am I missing something?


Are you sure the output you get from the "print j" is from the same loop
iteration as the "print i[0]"? Try adding "i" to the output.


Thank you for your timely response. Yes, I am sure "i" and "j" are
from the same iteration. I should point out that "i" actually has 8
elements and that str(i) gives a nice printout.


Thank you all for your interest in my problem. As Peter pointed out,
there was one row with zero elements in it and that's where my problem
was (of course it was the very last row, hence my confidence I have
"good" data).


A classic "don't be sure before you've tested". ;-)

Stefan

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


Re: List index out of range, but list has enough elements

2010-11-09 Thread Costin Gamenț
Thank you all for your interest in my problem. As Peter pointed out,
there was one row with zero elements in it and that's where my problem
was (of course it was the very last row, hence my confidence I have
"good" data).

Have a nice one,
Costin

On Tue, Nov 9, 2010 at 12:02 PM, Nitin Pawar  wrote:
> You may want to try a spilt if you are getting 8 different elements then it
> will give you a list of those elements
>
> On Tue, Nov 9, 2010 at 3:21 PM, Costin Gamenț 
> wrote:
>>
>> Thank you for your timely response. Yes, I am sure "i" and "j" are
>> from the same iteration. I should point out that "i" actually has 8
>> elements and that str(i) gives a nice printout.
>>
>> On Tue, Nov 9, 2010 at 11:33 AM, Stefan Behnel 
>> wrote:
>> > Costin Gamenț, 09.11.2010 10:24:
>> >>
>> >> Hi, I am trying to read a string as csv, but I encountered an odd
>> >> problem. Here's my code:
>> >>
>> >>        csvfile = csv.reader(datastr.split('\n'), delimiter=';')
>> >>        r = ''
>> >>        for i in csvfile:
>> >>                for j in i:
>> >>                        print j
>> >>                print i[0]
>> >>
>> >> the "print j" statement works, but "print i[0]" returns "IndexError:
>> >> list index out of range". Am I missing something?
>> >
>> > Are you sure the output you get from the "print j" is from the same loop
>> > iteration as the "print i[0]"? Try adding "i" to the output.
>> >
>> > Stefan
>> >
>> > --
>> > http://mail.python.org/mailman/listinfo/python-list
>> >
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>
>
>
> --
> Nitin Pawar
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Compare source code

2010-11-09 Thread Mark Wooding
Arnaud Delobelle  writes:

> python-mode has python-beginning-of-block (C-c C-u) and
> python-end-of-block.

Yes.  It was one of my explicit gripes that editing Python requires one
to learn entirely new and unfamiliar keystrokes for doing fairly
familiar editing tasks.

-- [mdw]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic/idiomatic?

2010-11-09 Thread Mark Wooding
Seebs  writes:

>   ' '.join([x for x in target_cflags.split() if re.match('^-[DIiU]', x)])
>
> This appears to do the same thing, but is it an idiomatic use of list
> comprehensions, or should I be breaking it out into more bits?

It looks OK to me.  You say (elsewhere in the thread) that you're stuck
with 2.4 compatibility.  I'd personally avoid the regexp, though, and
write this (actually tested with Python 2.4!):

' '.join(i for i in target_cflags.split()
   for p in 'DIiU' if i.startswith('-' + p))

> You will note that of course, I have carefully made it a one-liner so I
> don't have to worry about indentation*.

I failed at that.  You have to put up with my indentation.

-- [mdw]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List index out of range, but list has enough elements

2010-11-09 Thread Nitin Pawar
You may want to try a spilt if you are getting 8 different elements then it
will give you a list of those elements

On Tue, Nov 9, 2010 at 3:21 PM, Costin Gamenț wrote:

> Thank you for your timely response. Yes, I am sure "i" and "j" are
> from the same iteration. I should point out that "i" actually has 8
> elements and that str(i) gives a nice printout.
>
> On Tue, Nov 9, 2010 at 11:33 AM, Stefan Behnel 
> wrote:
> > Costin Gamenț, 09.11.2010 10:24:
> >>
> >> Hi, I am trying to read a string as csv, but I encountered an odd
> >> problem. Here's my code:
> >>
> >>csvfile = csv.reader(datastr.split('\n'), delimiter=';')
> >>r = ''
> >>for i in csvfile:
> >>for j in i:
> >>print j
> >>print i[0]
> >>
> >> the "print j" statement works, but "print i[0]" returns "IndexError:
> >> list index out of range". Am I missing something?
> >
> > Are you sure the output you get from the "print j" is from the same loop
> > iteration as the "print i[0]"? Try adding "i" to the output.
> >
> > Stefan
> >
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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


Re: List index out of range, but list has enough elements

2010-11-09 Thread Costin Gamenț
Thank you for your timely response. Yes, I am sure "i" and "j" are
from the same iteration. I should point out that "i" actually has 8
elements and that str(i) gives a nice printout.

On Tue, Nov 9, 2010 at 11:33 AM, Stefan Behnel  wrote:
> Costin Gamenț, 09.11.2010 10:24:
>>
>> Hi, I am trying to read a string as csv, but I encountered an odd
>> problem. Here's my code:
>>
>>        csvfile = csv.reader(datastr.split('\n'), delimiter=';')
>>        r = ''
>>        for i in csvfile:
>>                for j in i:
>>                        print j
>>                print i[0]
>>
>> the "print j" statement works, but "print i[0]" returns "IndexError:
>> list index out of range". Am I missing something?
>
> Are you sure the output you get from the "print j" is from the same loop
> iteration as the "print i[0]"? Try adding "i" to the output.
>
> Stefan
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List index out of range, but list has enough elements

2010-11-09 Thread Peter Otten
Costin Gamenț wrote:

> Hi, I am trying to read a string as csv, but I encountered an odd
> problem. Here's my code:
> 
> csvfile = csv.reader(datastr.split('\n'), delimiter=';')
> r = ''
> for i in csvfile:
> for j in i:
> print j
> print i[0]
> 
> the "print j" statement works, but "print i[0]" returns "IndexError:
> list index out of range". Am I missing something?

Change

print i[0]

to

print i

You'll see that there are empty rows in your data. You cannot detect these 
rows with

for j in i:
   print j

because you get zero iterations, i. e. the 

print j 

statement is never executed for these rows.

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


Re: Pythonic/idiomatic?

2010-11-09 Thread Peter Otten
Seebs wrote:

> I have an existing hunk of Makefile code:
> CPPFLAGS = "$(filter -D* -I* -i* -U*,$(TARGET_CFLAGS))"
> For those not familiar with GNU makeisms, this means "assemble a string
> which consists of all the words in $(TARGET_CFLAGS) which start with one
> of -D, -I, -i, or -U".  So if you give it
> foo -Ibar baz
> it'll say
> -Ibar
> 
> I have a similar situation in a Python context, and I am wondering
> whether this is an idiomatic spelling:
> 
> ' '.join([x for x in target_cflags.split() if re.match('^-[DIiU]', x)])
> 
> This appears to do the same thing, but is it an idiomatic use of list
> comprehensions, or should I be breaking it out into more bits?

You may be able split and match with a single regex, e. g.

>>> cflags = "-Dxxx -D zzz -i- -U42-U7 -i -U"

>>> re.compile(r"-[DIiU]\S*").findall(cflags)
['-Dxxx', '-D', '-i-', '-U42-U7', '-i', '-U']

>>> re.compile(r"-[DIiU]\s*(?:[^-]\S*)?").findall(cflags)
['-Dxxx', '-D zzz', '-i', '-U42-U7', '-i ', '-U']

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


Re: List index out of range, but list has enough elements

2010-11-09 Thread Stefan Behnel

Costin Gamenț, 09.11.2010 10:24:

Hi, I am trying to read a string as csv, but I encountered an odd
problem. Here's my code:

csvfile = csv.reader(datastr.split('\n'), delimiter=';')
r = ''
for i in csvfile:
for j in i:
print j
print i[0]

the "print j" statement works, but "print i[0]" returns "IndexError:
list index out of range". Am I missing something?


Are you sure the output you get from the "print j" is from the same loop 
iteration as the "print i[0]"? Try adding "i" to the output.


Stefan

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


Re: Compare source code

2010-11-09 Thread Lawrence D'Oliveiro
In message , Ethan 
Furman wrote:

> Lawrence D'Oliveiro wrote:
>
>> In message , Tim Harig wrote:
>>>
>>> I personally prefer tabs as it lets *me* decide how far the apparent
>>> indentations are in the code.
>> 
>> But they don’t. Other people can have different settings, and they will
>> see different indentations for your code
> 
> That's exactly the point -- each person can decide what level of
> indentation they prefer to look at.

But I thought Mr Harig was referring to “*me*” as in the author of the code, 
not the reader.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: JavaScript vs Python

2010-11-09 Thread Lawrence D'Oliveiro
In message , Chris 
Rebert wrote:

> On Mon, Nov 8, 2010 at 10:52 PM, Lawrence D'Oliveiro
>  wrote:
>
>> Because JavaScript is actually a decent language in its own right.
> 
> "The Good Parts" of it anyway.

Python, too, has its good parts, you have to admit...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if a module exists?

2010-11-09 Thread Lawrence D'Oliveiro
In message , Roy Smith wrote:

> Fail early and often, that's what I say.

Good advice that could apply to lots of things. Except maybe procrastination 
... :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Silly newbie question - Caret character (^)

2010-11-09 Thread Lawrence D'Oliveiro
In message , Seebs wrote:

> The publisher doesn't care whether the books are accurate ...

A sad state for the once-proud name “Osborne” ...
-- 
http://mail.python.org/mailman/listinfo/python-list


List index out of range, but list has enough elements

2010-11-09 Thread Costin Gamenț
Hi, I am trying to read a string as csv, but I encountered an odd
problem. Here's my code:

csvfile = csv.reader(datastr.split('\n'), delimiter=';')
r = ''
for i in csvfile:
for j in i:
print j
print i[0]

the "print j" statement works, but "print i[0]" returns "IndexError:
list index out of range". Am I missing something?
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >