Re: Style question for conditional execution

2010-11-24 Thread Asun Friere
On Nov 25, 7:43 am, Paul Rubin  wrote:
> Gerald Britton  writes:
> >     if v:
> >         f()
>
> > I might, however, think more in a functional-programming direction.
> > Then I might write:
>
> >     v and f()
>
> Python has conditional expressions.  The above would be:
>
>     f() if v else None
>
> using "and" is bug-prone.

Using 'and' is indeed bug-prone when used in combination with 'or' to
achieve a ternary conditional op, as was done the pre PEP308 days, eg
"val = cond and a or b" because of the possibility that 'a' was itself
not true, (thus requiring the ugly 'val = (cond and [a] or [b])[0]').

But no such bug could occur with this particular idiom. What could
possibly go wrong here? :)

That being said, I agree with previous posters that "if cond : fn()"
wins in terms of readability.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DTD Parsing

2010-11-10 Thread Asun Friere
On Nov 10, 5:00 pm, Stefan Behnel  wrote:

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

Yes I should take the time to familiarise myself with the lxml API in
general. I mostly use libxml2 and libxslt nowadays.  For simple stuff
(like this) I use a StateParser which is your common-or-garden variety
State Pattern built on HTMLParser.  (For the record it took 3 trivial
state definitions and one hackish one :)

However, my issue was not with any particular in any particular python
technology for XML processing, but with eating a DTD.  Once it's in
xsd, it's all downhill from there! So the answer to my question turned
out to be dtd2xsd.pl :)

> 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.

It's very simple really.  I would like to know whether there is some
generally used DTD parser around which could function as a replacement
for xmlproc's DTDParser/DTDConsumer, the existence of which might have
evaded my attention.  I would still like to know.

Without wanting to appear ungrateful, I'm not after any shortcut to
any goal, hidden or otherwise, nor is the reason I want a DTD Parser
(I only told you because you asked so nicely) strictly pertinent to my
question.  I simply meant to ask, precisely what I did ask.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DTD Parsing

2010-11-10 Thread Asun Friere
On Nov 10, 6:36 pm, Ian Kelly  wrote:

> 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.  

For myself, generally because I only become aware of the module, or
the module is only written after I written some stuff myself.

I wrote a Date object before the standard one either existed or I knew
of it and I'll keep on using it till you pry it from my cold ... on
2nd thoughts don't pry, just let me use it.
-- 
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 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


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: python command line manual

2010-05-24 Thread Asun Friere
On May 25, 8:52 am, Peng Yu  wrote:
> I mainly check online python manual. But I feel that it would be nice
> if there is command line manual available (just like perl command line
> manual). Could you please let me know if such command line manual
> available?
>
> --
> Regards,
> Peng

It's not really a manual, but if you want the documentation written
into a module try 'pydoc '.  This is gives you the same output
as you get running help() in the python shell.




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


Re: enhancing 'list'

2010-01-17 Thread Asun Friere
On Jan 18, 9:37 am, samwyse  wrote:
> Consider this a wish list.  I know I'm unlikely to get any of these in
> time for for my birthday, but still I felt the need to toss it out and
> see what happens.
>
> Lately, I've slinging around a lot of lists, and there are some simple
> things I'd like to do that just aren't there.
>

If memory serves me correctly, it has been possible to subclass 'built-
in' types since Py2.2 or thereabouts.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Apple Mac OS X 10.6 support & compatability with Python 3 ?

2009-12-16 Thread Asun Friere
On Dec 17, 4:41 am, pdlem...@earthlink.net wrote:

> Does anyone have experience with OS X ? Could I use WConio in a
> Windows emulator ?  I have no experience with MACs and am debating
> whether to send this back before opening.

You don't need an emulator per se.  You can reboot a Mac into Windows
using 'BootCamp' (comes with OSX, you supply the copy of XP),
alternatively you can run Windows in a Virtual Machine using 3rd party
software such as 'Parallels' (which I use to run Xubuntu on an iMac)
or 'VMWare' which is nice because you can use multiple OSen
simulatneously (and get them to talk to each other).  Yes, you can
have it all!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: switch

2009-12-11 Thread Asun Friere
On Dec 11, 1:38 am, Tim Chase  wrote:

> It's clean if it were the solution to my problem

Picking out that line first, just to be clear about this.

You missed the disclaimer.

This was never meant to be a solution to your problem.  It was
solution to the problem contained in the code you posted.

Carl, asked a question, in response you provided an example, and I
wrote a solution.  I did so to in order to illustrate how something
resembling a dispatch mechansism can save a programmer from ending up
with a "rat's-nest" of elif chainage.  I hope you did not
misunderstand me as advocating your pulling apart working production
code.  Heck, I wouldn't, err ...don't, do this.

Which is _not_ to say that it isn't actually a solution your problem
as well! :)


>>[One guy analogy]
>
> This is where you make a false assumption

Again "I don't really know your problem only the code you've posted."
If I misunderstood the record types as originating from different
providers, I'm sure you will find that my code, which faithfully
reimplements yours, does not.

> -- the contents and
> parsing of the "switch" are provider-specific in this case,
> mapping to a common ontology of the Phone object:
>
> class MonopolyProvider1Parser:
>   ...
>   switch row['recordtype']:
> case '01':
>   phone.international += Decimal(row['internationalcost'])
>   // optionally a "break" here depending on
>   // C/C++/Java/PHP syntax vs. Pascal syntax which
>   // doesn't have fall-through
> case '02':
>   phone.text_messaging += (
> int(row['textmessages sent']) +
> int(row['pages received']) +
> int(row['textmessages sent']) +
> int(row['pages received'])
> ...
> default:
>   raise WhatTheHeckIsThis()
>
> class MonopolyProvider2Parser:
>   ...
>   switch row['recordtype']:
> case 'abc':
>   phone.international += (
> Decimal(row['canada cost']) +
> Decimal(row['eu cost']) +
> Decimal(row['mexico cost']) +
> Decimal(row['other intl cost'])
> )
> case 'xyz':
>   phone.text_messaging += int(row['textmessages'])
> ...
> default:
>   raise WhatTheHeckIsThis()
>
Fair enough. What you posted was a subset of your overall problem.
Obviously!

Inasmuch as the code that you posted accurately represents a subset of
your problem, the solution given is still applicable, at least to that
subset of your problem.  It's just that each inidividual
MonopolyProvider will require its own set of data sources.  In any
case, I'm sure you could work out it could be applied, if you put your
mind to it.

I agree this involves more code than the example required, possibly
for less gain and I believe it is still advantageous to organise the
code in a way which separates knowledge from logic.  At least when
that knowledge is non-trivial.

> > # The one thing I'm sure I don't understand from the code is where the
> > original rectypes comes into the process.
>
Sorry, my worrying there about whether we need to look the appropriate
RecType up in that dict was just a distraction.  The problem isn't in
the dict, but with that the try should only be trapping unknown types,
not problems of instantiation.  I should have written:
 try :
AppropriateRecType = rectypes[rectype]
except KeyError :
raise WhatTheHeckIsThisError('unknown rectype: %s' % rectype)
record = ApproriateRecType(row)

>  From the provider data -- sometimes CSV files, sometimes
> tab-delimited text files, sometimes MS Access MDB files,
> sometimes a web service...
> varies per-provider (and some providers
> have multiple formats, like Verizon has MyBIZ and IBAS; ATT has
> their WinCD and Premier; etc).  No two formats are the same, so
> the logic needed to parse the data into our internal homogenized
> Phone data structure varies per each one.  And the logic (or lack
> thereof) used by many providers in creating their formats require
> reverse-engineering most of them through trial-and-error, and
> huge ugly if/elif/else chains.

I feel your pain, I really do ... and a dispatch mechanism could
relieve some of it. ;)

Now I'm not saying you should implement it on extant production code.
As I wrote above, I still use, and unfortunately maintain, older code
which is a hideous mess of elif chains.  The task of challenging these
elif chains is daunting, and rewriting such working code won't rank in
my work priorities for the foreseeable future.

This is why, elif chains, when they first arise, or better perhaps,
when they first begin to grow, should be examined to see whether they
are a bud that ought to be nipped, whether they sensibly can be
nipped, and if so how.  They are, in Carl's words, "red flags," at
least they are if your're "not a very good progammer," like me.  I
invite all my fellow NVGPs to treat them as such as w

Re: switch

2009-12-10 Thread Asun Friere
On Dec 10, 6:57 am, Tim Chase  wrote:
> Carl Banks wrote:
> > What if the object is a string you just read from a file?
>
> > How do you dispatch using polymorphism in that case?
>
> This is where I most miss a switch/case statement in Python...I
> do lots of text-file processing (cellular provider data), so I
> have lots of code (for each provider's individual format) that
> looks like
>
>phones = {}
>for row in csv.DictReader(file('data.txt', 'rb')):
>  phonenumber = row['phonenumber']
>  if phonenumber not in phones:
>phones[phonenumber] = Phone(phonenumber)
>  phone = phones[phonenumber]
>  rectype = rectype
>  if rectype == '01':
>phone.international += Decimal(row['internationalcost'])
>  elif rectype == '02':
>phone.text_messaging += (
>  int(row['textmessages sent']) +
>  int(row['pages received']) +
>  int(row['textmessages sent']) +
>  int(row['pages received'])
>  elif rectype == ...
> ...
>  else:
>raise WhatTheHeckIsThis()
>

Great example Tim.   This is something that many of us must be dealing
with on a daily basis.  The problem has enough details (bar one), to
allow an answer and not so detailed as to be confusing.  And for me
it's a particularly good example, because your need accommodate
mulitple provider formats makes me feel right at home.

> which would nicely change into something like
>
>switch row['recordtype']:
>  case '01':
>phone.international += Decimal(row['internationalcost'])
>// optionally a "break" here depending on
>// C/C++/Java/PHP syntax vs. Pascal syntax which
>// doesn't have fall-through
>  case '02':
>phone.text_messaging += (
>  int(row['textmessages sent']) +
>  int(row['pages received']) +
>  int(row['textmessages sent']) +
>  int(row['pages received'])
>  ...
>  default:
>raise WhatTheHeckIsThis()

Cleaner yes.  But, with respect, not so clean as to justify the
construct.  Following my advice you might express that switch
statement like so:

phone.update_from_record(record)

It is, in this context, completely irrelevant observe that 'dispatch'
originally referred specifically to the dismissal of ambassadors.  It
may be slightly more to the point to tap into the wisdom of Henry Ford
and turn your design inside out.

This switch statement belongs to one guy.  One guy who wants to know
how to do everything that needs to be done to Phones no matter who
asks.  Let's install a conveyor belt instead!

Standard Disclaimer:  Untested (obviously); just a sketch; I don't
really know your problem only the code you've posted; etc etc.

First some minimal "architecture":
---
#The first class your already have. We just need one more method

class Phone (object) :
...
def update_from_record (self, rec) :
return rec.updatePhone(self)


#and then some "data source" classes

class RecType (dict) :
def __init__ (self, row) :
...

class RecType_001 (RecType) :
def updatePhone(self, phone) :
phone.interational += Decimal(self['internationalcost'])

class RecType_002 (RecType) :
def updatePhone(self, phone) :
phone.text_messaging += (
int(self['textmessages sent']) +
int(self['pages received']) +
...

#and if we must ...
rectypes = {'01':RecType_001, '02': RecType_002, ...}

# The one thing I'm sure I don't understand from the code is where the
original rectypes comes into the process.
#I would prefer, if it's possible, just thowing the appropriate class
in rather than looking up this dict to instantiate.
---

Now the different providor types, previously the bane of your
existence, are your staff.  Your original code will now read something
like:

phones = {}
for row in csv.DictReader(open('data.txt', 'rb')) :
try :
record = rectypes[rectype](row)
except KeyError :
raise WhatTheHeckIsThisError('unknown rectype: %s' % rectype)
phonenumber = record.phonenumber
if phonenumber not in phones :
phones[phonenumber] = Phone(phonenumber)
phone = phones[phonenumber]
phone.update_from_record(record)

I wonder if you agree that it's bit cleaner now?  It's an effective
solution. I'm making no representation that it's the best.

I like think largely because it contains the knowledge accessibly.  If
you have "lots of code" that deal with this kind of thing, chances are
library of core data source classage could reduce much of it to a
simple (and legible!) one liner.  A provider "enhances" their format,
or a new provider format is added, code in one class, not in every
switch they might be involved in.  But sorry, I don't mean to
patronise, I'm sure you know the spiel.

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


Re: switch

2009-12-10 Thread Asun Friere
On Dec 10, 2:00 pm, Carl Banks  wrote:
> On Dec 9, 5:02 pm, Asun Friere  wrote:
>
> > On Dec 9, 7:08 pm, Carl Banks  wrote:
>
> > > What if the object is a string you just read from a file?
>
> > > How do you dispatch using polymorphism in that case?
>
> > This would be a pertinent question, were I advocating that _all_
> > switch statements should, or even can, be replaced with "dispatch
> > using polymorphism."
>
> Then why did you claim that a decent OO should never have a switch
> statement then?

The mere fact that it is possible to demonstrate a use of the 'goto'
statement, which does not offend against a program's structural
integrity, does not mean it's necessarily a good idea to have it lying
about given that in the large majority of cases it leads to
(encourages?) bad code.  Python sagely declined to implement 'goto'.

I feel the same considerations apply in regard to the switch/case
statement in the context of a true* OO (ie python but not java ;>).
Imo the decision not to implement a switch statement was wise.  This
is not to deny that a traditional switch is not in often a sane
solution.  I just think that if your elifs are getting unwieldy enough
to require the application of the proverbial layer of abstraction,
then a switch statement fails to deliver sufficient abstraction.

> You argued that a decent language OO should never
> have a switch statement because polymorphic dispatch is the right way
> to handle it in OO languages, which implies that polymorphism can and
> should take the place of any switch statement.

That is a misreading.  I wrote, that the case logic is "probably"
symptomatic of poor design. I advocated "considering" whether an OO
solution might be more appropriate.  You misunderstand my intent.  I'm
not here to postulate some ultimate OO truths, but to provide
practical advice (aimed here mainly at Hong and Kee).  In regard elif
chains, this is my advice.

If you see too many elifs in your code (or if you find yourself
wishing for a switch statement) alarm bells should start to go off.
STOP, give serious consideration as to whether applying some patterns
or similar will improve the design, and HINT:  first consider whether
that pattern might be something resembling a dispatch mechanism, it's
just downright spooky how in real-life programming situations this
turns out to be the answer.  Obviously the answers to these questions
are not invariably 'yes.'  Often enough they are.

>
> > What if, instead of reading strings from a file,
>
> Why don't you answer my question first,

Because, as I have already explained, I object to the question.  It
presupposes my holding a position I don't.

But look perhaps I'm being unfair to you Carl.  I presumed your
question was rhetorical, or at least you supposed it disproved
whatever it is you were attacking.  If instead you were asking for
clarification, the short answer is "wrap as you read."  A longer
answer is in the response to Tim, I'll send in a while.

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


Re: switch

2009-12-09 Thread Asun Friere
On Dec 9, 7:08 pm, Carl Banks  wrote:
> What if the object is a string you just read from a file?
>
> How do you dispatch using polymorphism in that case?

This would be a pertinent question, were I advocating that _all_
switch statements should, or even can, be replaced with "dispatch
using polymorphism."

What if, instead of reading strings from a file, you are parsing, say
xml, into an object framework isomorphic to the file's schema?  And
no, this is not a contrived example.  Now you want to print out the
structure, or a branch thereof.  To make matters interesting you want
to be able to print it out in a number of different formats.  So we
have:

  5 def print_out (element, fmnt) :
  6 if element.__class__ is schema.Title :
  7 if str(fmnt) == 'html' :
  8 print_out_spam_title(element)
  9 elif str(fmnt) == 'txt' :
 10 print_out_ham_title(element)
 11 elif 
 12 elif element.__class__ is schema.Paragraph :
 13 if str(fmnt) == 'html' :
 14 print_out_spam_paragraph(element)
 15 elif str(fmnt) == 'txt' :
 16 print_out_ham_paragraph(element)
 17 elif ...
 18 elif element.__class__ is ...
 19 ...
 20

And so on for a dozen or so tags and 3 formats.  And imagine the joy
of adding the 4th or 5th format.

Now I guess you already realise that applying a dispatch mechanism
here will improve the design and result in code that is dryer, far
more easily extensible and arguably (but only arguably) more readible?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: switch

2009-12-09 Thread Asun Friere

On Dec 9, 5:39 pm, Steven D'Aprano
 wrote:
> On Tue, 08 Dec 2009 21:36:23 -0800, Asun Friere wrote:
> > On Dec 9, 4:02 pm, Kee Nethery  wrote:
> >> I string together a bunch of elif statements to simulate a switch
>
> >> if foo == True:
> >>         blah
> >> elif bar == True:
> >>         blah blah
> >> elif bar == False:
> >>         blarg
> >> elif 
>
> > This code is probably symptomatic of poor design. (Not to mention that
> > your condition tests).  For which reason python has no 'case' statement
> > and why no decent OO language should.
>
> That's a provocative statement.
>

My reply was lost in the aether, so here goes again.

If it's provocative, it is at least hedged.  It is merely symptomatic
and only probably so, because there are numerous instances where case
logic is the only sensible solution.  I'm not advocating some cargo-
cult rule for the elimination of all uses of elif.  If I were I would
rightly be presented with numerous code examples where a switch is a
sensible option, much as happens when someone pronounces against the
humble goto statement.


> > It is a principle of OO design that "an object should know what to do
> > itself."  Rather running an object though a series of tests, it is
> > better to send the object a message, relying on polymorphism or duck-
> > typing, and deal with any exceptions thrown.
>
> Perhaps that's true, but you'll note that the example given above doesn't
> run a single object through a series of tests, but runs a series of tests
> on DIFFERENT objects, to find the first which matches.
>

Well actually two objects with one being tested twice.  But you are
right, I was being sloppy when I wrote "running an object" especially
in light of the fact that the following clause makes more sense when
run against objects of potentially different class.  Same for dispatch
mechanisms of course.

What I'm saying is that when you find a large if/elif/else in your
code, regard it with suspicion and "consider" whether better design
might not eliminate it.  And I'm speaking as someone who still has to
maintain some code (in perl not python) which has an if/elif/else
statement spanning 5 A4 pages.  What's worse, I was the one who did
this to myself some 8 years ago.

What I'm also saying is "learn about dispatch mechanisms," they are
about the most useful patterns out there (next to the State pattern).
As a matter of practice I have found that more often than not, large
case statements can better be solved using double-dispatch.  Obviously
not all.  Obviously!

> But putting that aside, I find myself wondering how you would deal with
> the following switch-like series of tests.
>
> def print_grades(score):
>     if not 0 <= score <= 100:
>         raise ValueError("score must be between 0 and 100")
>     if score < 50:
>         print "You have failed."
>         consider_suspension()
>     elif score == 50:
>         print "You have just passed by the skin of your teeth."
>     elif score < 60:
>         print "You have scored a D. You need to try harder."
>     elif score < 70:
>         print "You have scored a C."
>     elif score < 80:
>         print "You have scored a B. Well done."
>     elif score < 100:
>         print "Congratulations, you have scored an A."
>     else:
>         assert score == 100
>         print "You have scored a PERFECT 100% SCORE!!!"
>         if not evidence_of_cheating():
>             call_newspapers()
>
> Obviously that could, with a non-trivial amount of work, be turned into a
> dictionary dispatch, but is the benefit worth the extra effort?
>

Probably not.  Depending on the nature of the app, I'd probably be
calling score.print_grades() and using cutoff values of 85, 75, 60 and
50 (perhaps not even hardcoded into the logic), but sure this is a
fine example of a place where a solution other than a simple switch
would be overkill.  As such this example would be a good counter to
the absolute repudiation of case logic I did not make.  I doubt,
however, that it is of great pedagogic value in alerting programmers
to the design options available to them in overcomming what the
perceive as a lack in the language.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: switch

2009-12-08 Thread Asun Friere
On Dec 9, 5:12 pm, Steven D'Aprano
 wrote:
> On Tue, 08 Dec 2009 21:02:44 -0800, Kee Nethery wrote:
> > I string together a bunch of elif statements to simulate a switch
>
> > if foo == True:
> >    blah
> > elif bar == True:
> >    blah blah
> > elif bar == False:
> >    blarg
> > elif 
>
> Are you sure you want to test for equality with True and False? Generally
> one should write that as:
>
> if foo:
>     blah
> elif bar:
>     blah blah
> elif not bar:
>     blarg
> ...
>
> --
> Steven

I was going to point that out, but thought it a little OT.  One might
also mention that testing for "if foo is None :" is a special case.
I'm also having a bit of a problem imagining what the subsequent
conditions must be which make testing "elif not bar" subsequent to
testing "elif bar" necessary, but that's just me.

Back OT, one would hope not to encounter python code with a long chain
of elifs like that.  Probably the design should be improved, or where
this would be overkill, use the dictionary trick.

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


Re: switch

2009-12-08 Thread Asun Friere
On Dec 9, 4:02 pm, Kee Nethery  wrote:
> I string together a bunch of elif statements to simulate a switch
>
> if foo == True:
>         blah
> elif bar == True:
>         blah blah
> elif bar == False:
>         blarg
> elif 


This code is probably symptomatic of poor design. (Not to mention that
your condition tests).  For which reason python has no 'case'
statement and why no decent OO language should.

It is a principle of OO design that "an object should know what to do
itself."  Rather running an object though a series of tests, it is
better to send the object a message, relying on polymorphism or duck-
typing, and deal with any exceptions thrown.

Generally if you find yourself wanting to use a 'case' statement or
writing a series of if/elif which involves more than say, three,
elifs, condsider whether you cannot use a double
dispatch mechanism instead.

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


Re: Evil trend report - cancelled

2009-09-07 Thread Asun Friere
On Sep 7, 1:07 pm, John Nagle  wrote:
>
>     Accidentally posted a private e-mail.  Cancelled.  Sorry.
>

You think you can get out of it that easily?  You've exposed yourself
as an enemy of the Empire now!  You'd better look over your shoulder
for guys dressed in black cloaks breathing heavily ... ;)


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


Re: Web Services examples using "raw" xml?

2009-08-24 Thread Asun Friere
On Aug 25, 5:41 am, John Gordon  wrote:

>
>   File "/usr/lib/python2.3/site-packages/suds/client.py", line 59
>     @classmethod
>     ^
> SyntaxError: invalid syntax
>

If memory serves me correctly, decorators were introduced in
python2.4.  That would account for your SyntaxError.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hashability

2009-08-12 Thread Asun Friere
On Aug 12, 5:14 pm, Dennis Lee Bieber  wrote:

> c1 = C()
> c2 = C()
>
> {c1:4}[c2]
>
> to behave? That IS the equivalent of your statement -- two instances are
> two distinctly different entities...
>

Thankyou, that is EXACTLY the mistake I made that sent me off into
lunacy.

At the risk of further embarassment, the answer is that one would
expect it to behave analogously to:

c1 = int(x)
c2 = int(x)

{c1:4}[c2]

Or is my brain still on vacation?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hashability

2009-08-12 Thread Asun Friere
On Aug 12, 4:52 pm, James Stroud 
wrote:

> Sorry for being a twit.

Don't be ridiculous.  You haven't been a twit, I have!

I've just had a complete "blonde" moment here (with apologies to any
real blondes out there.  My only excuse is that I've been up to 02:30
for the last three nights running (or maybe it's the ageing process, a
cerebrovascular accident or something).

I just checked a class I recently wrote specifically for the purposes
of hashing a dict (in case I had made this error IRL).  Wouldn't you
know it, it's subclassed to tuple, and defines both __eq__ and
__cmp__.  Luckily when I write production code the guy who knows what
he's doing takes over.  And this in an app which compares keys from
different pickled files (representing DB holdings)?!  Of all things.

I can't believe how unfathomably stupid I've been.  I'm extremely
embarassed.  I think I'll just go out and shoot myself now.  Or get
some sleep.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hashability

2009-08-11 Thread Asun Friere
On Aug 12, 3:52 pm, Chris Rebert  wrote:

> Thought Experiment:
> Consider, for each dict, the case of pickling it twice to 2 separate files.
> When loaded from both files into the same program, the spam-ham dicts
> will work as expected between each other.
> The dicts with C()s will not. For example, assuming the unpickled
> dicts are `cs1` and `cs2`, cs1[cs2.keys()[0]] will raise KeyError.
>

Aha!

cheers.

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


Re: hashability

2009-08-11 Thread Asun Friere
On Aug 12, 3:32 pm, James Stroud 
wrote:

> You should be more imaginative.

I'm by no means discounting that there might be some actual problem
you're trying to solve here, but I honestly can't see it.

There really is no need to get personal about this, so rather than
asking for a level of imagination from me, (which I apparently lack),
please just explain to me how {one_instance_of_a_hashable_class : val,
another_instance_of_a_hashable_class :val} is conceptually different
{one_instance_of_class_str: val, another_instance_of_class_str: val},
in terms of persistence.

If I am missing something here, I would actually like to know.  If on
the other hand, I'm not, then rather at taking umbrage, you might want
instead to save yourself the effort of solving a non-existent problem?

> Can you come give a class to my users?

No.

However, I think it's fairly central to the notion of a class that it
is a template for creating different instances which themselves have a
unique identity.  And that subsequent calls to a class' constructor
ought to create unique instances of that class (subject perhaps to
implementation tricks such as interning).  If it is not obvious that {C
():4}[C()] invovles subsequent calls to C's constructor, then that
very example is itself didactic.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hashability

2009-08-11 Thread Asun Friere
On Aug 12, 12:15 pm, James Stroud  wrote:

> I realize I left out my use. The intent of the function is to flag
> objects that will make useful keys for a persistent dictionary. The
> {C():4}[C()] example demonstrates why I want to avoid certain types of
> keys--I don't want users to do things like {C():4, C():4}, which python
> happily allows but falls apart at the level of persistence.

What am I missing here?  How, in terms of persistence, is {C():4, C():
4} conceptually different from {'spam':4, 'ham':4}?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hashability

2009-08-11 Thread Asun Friere
On Aug 12, 10:54 am, James Stroud  wrote:

> I wrote the function to test hashability of arbitrary objects. My reason
> is that the built-in python (2.5) hashing is too permissive for some
> uses. A symptom of this permissiveness comes from the ability to
> successfully hash() arbitrary objects:

Arbitrary, or anonymous objects and some uses or some users?  I'm
can't see why anyone would expect different instance of a class to be
equivalent keys.

> The basis for the exception is that the two instances do not have the
> same hash() although conceptually they might seem equal to the
> unitiated.

Perhaps the best solution would be for the unitiated to correct their
misaprehensions?  If you don't understand that you are instantiating a
number of anonymous instances of a class you are missing something
very fundamental.

> Were I to re-design python, I'd throw an exception in this
> case because of the ill-defined behavior one might expect if a C()
> serves as a key for a dict.

Then you couldn't to this:

d = {C():1, C():2, C():3}
a,b,c = d.keys()
d[c]

Anonymous instances are a GoodThing(tm) and they can usually be de-
anonymised if need be.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Announcing PythonTurtle

2009-08-03 Thread Asun Friere
On Aug 4, 6:35 am, r  wrote:

[snip]

>
> I can remember the first time i used turtle (in python stdlib) and i
> kept saying to myself...
>
>     "Were the heck is this damn turtle?!?!" (>_<)
>
> :-)

In Python2.6, try this:
>>> turtle.shape('turtle')

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


Re: Can module tell if running from interpreter vs Windows command line ?

2009-07-15 Thread Asun Friere
On Jul 16, 2:14 pm, alex23  wrote:

...

> AND
> you're citing back what I myself wrote in the link to which I also
> referred the OP - whom (sic) has subsequently posted his success with this
> technique - so I'm not really sure what the point is here other than
> "if you have a different use case, you'll need a different
> solution"...
>

Please don't take offence where none was intended.  I know that I was
citing you and that I was highlighting the caveat you raised,
explicitly so.  No criticism of your post was intended nor implied.
Moreover the fact that it worked for OP on a single occasion does not
speak for its robustness.

> > Depending on the use case, it is of course easy to tell whether the
> > module was executed on the command line, or imported (from an
> > interactive shell or another script) using the __name__ trick.  (eg.
> > is_imported = __name__ == '__main__')
>
> That should be:
>
> is_imported = __name__ != '__main__'
>

Doh! ... Yup I actually used that when I tried it out, my bad.

> And such a test is all well and good if the main code body is the one
> that needs to know about the execution mode, but if you need to know
> under which conditions the program is being run within a module
> imported by the main body, well, that check is _always_ going to be
> true...

Which is what the paragraph you just quoted says.  Hence the attribute
is called 'is_imported' rather that 'running_non_interactively'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can module tell if running from interpreter vs Windows command line ?

2009-07-15 Thread Asun Friere
On Jul 16, 10:47 am, alex23  wrote:

...

> This older post should 
> help:http://groups.google.com/group/comp.lang.python/browse_frm/thread/6c5...
>
> But the quick answer is to import sys into your program, and do a test
> on hasattr(sys, 'ps1'), which is only created when running the
> interactive prompt.

As you note there, this will work when running the vanilla shell (ie
running  it from the command line), but not (potentially) in other
interactive environments (IronPython being the example you give).
Another instance:  there is not sys.ps1 when running a python shell
under idle.  Since this solution differs whether the interactive
session is taking place from the cmd line, idle, IronPython etc. it
seems to me not terribly robust.

Depending on the use case, it is of course easy to tell whether the
module was executed on the command line, or imported (from an
interactive shell or another script) using the __name__ trick.  (eg.
is_imported = __name__ == '__main__')


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


Re: missing 'xor' Boolean operator

2009-07-15 Thread Asun Friere
On Jul 15, 5:44 pm, Mark Dickinson  wrote:
> On Jul 15, 5:07 am, "Dr. Phillip M. Feldman" 
> wrote:

[snip]

> >    for arg in args:
> >       if bool(arg): result= not result
>
> It's more idiomatic to say "if arg: ..." rather than "if bool
> (arg): ...".
>

Ah yes, but not once conditional tests, (just like logical operators),
type-check to ensure they have been supplied with Boolean entities. ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Clarity vs. code reuse/generality

2009-07-07 Thread Asun Friere
On Jul 7, 3:05 pm, Steven D'Aprano  wrote:

[snip]

> Sense is, if you like, a "signed direction".

Or to put it another way, in the graphical representation of a vector,
'direction' is the line, 'sense' is the arrowhead.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Good books in computer science?

2009-06-19 Thread Asun Friere
On Jun 15, 1:00 am, rustom  wrote:
>
> For every one Horowitz there are a thousand wannbes thumping on the
> piano trying to become Horowitz.
> The traction that practice gives is maximal only in the beginning.

Funny but I was watching an interview/conversation between and older
composer and a young up and coming WFCP (World Famous Concert Pianist)
the other day.  The composer had been teaching the pianist to
understand the works he was playing ... anyway, the old guy remarked
that when he was younger he wanted to be a WFCP too, but that he
lacked a crucial ability that the young star had.  What was it? "I
lack the ability to make myself practise as well and for as long as
you do."


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


Re: waling a directory with very many files

2009-06-17 Thread Asun Friere
On Jun 15, 6:35 am, Andre Engels  wrote:
> What kind of directories are those that just a list of files would
> result in a "very large" object? I don't think I have ever seen
> directories with more than a few thousand files...


(a...@lucrezia:~/pit/lsa/act:5)$ ls -1 | wc -l
  142607

There, you've seen one with 142 thousand now! :P
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regarding Python is scripting language or not

2009-06-17 Thread Asun Friere
On Jun 18, 5:03 am, Terry Reedy  wrote:

> That depends on what you mean by 'put into classes' (and 'everything').
>
> If you mean 'be an instance of a class', which I think is the most
> natural reading, then Python *is* object-oriented and, if I understand
> what I have read correctly (so that ints are just (unboxed) ints and not
> members of an int class), Java *is not*!

+1

This needs to be said to those who imagine, because you have to code
the class explicitly in Java whereas Python objects can be manipulated
in ignorance of the idea of class, that Java is somehow OO in the way
Python is not.

OTOH the whole notion of defining OO by the use of classes
automatically excludes from consideration prototype-based OO languages
(eg. Self) which arguably offer a purer approach to OO than class
centric languages.




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


Re: newbie question

2008-11-27 Thread Asun Friere
On Nov 27, 9:05 pm, Bruno Desthuilliers  wrote:

> The problem is that you often have more to do in the __main__ section of
> a script than just calling one simple function, and you don't
> necessarily want to pollute the module's namespace with all this code.

As I said, it's probably just me ;)  I'm not sure I understand,
however, why calling multiple functions under 'if __name__ ...' will
pollute the namespace if these functions are already defined there?

Eg.

def foo (arg) :
#stuff
return exit_status
def bar (arg) :
#stuff
return exit_status
def main (argv) :
#parse args
#call and do stuff with foo and bar
return exit_status

if __name__ == '__main__' :
import sys
sys.exit(main(sys.argv))

Doesn't this just pollute the namespace with main()?

Surely you should be structuring the code above the test to minimise
namespace pollution.




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


Re: newbie question

2008-11-26 Thread Asun Friere
On Nov 27, 6:11 am, Nan <[EMAIL PROTECTED]> wrote:
> Hello,
>    I just started to use Python. I wrote the following code and
> expected 'main' would be called.
>
> def main():
>   print "hello"
>
> main

Not an answer to your question, but I dislike functions named 'main'
because the situation they occur in would better be dealt with by
exploiting the name of the built-in module '__main__'.  But maybe
that's just me.

However, consider your code rewritten thusly:

def greet () :
print "hello"

if __name__ == '__main__' :
greet()

(A more literal translation of your program would be:
if __name__ == '__main__' : print 'hello')

This little trick ensures that greet() will execute if the module is
itself executed as a script, but that it won't if you import it from
elsewhere (ie. another script or the intepreter).

IMHO, it's good practice, wherever you may be tempted to write 'def
main()', intending this to be the glue code for your various functions
etc, instead to test whether the code is running as __main__ as above.
--
http://mail.python.org/mailman/listinfo/python-list


Re: import foo vs. python -m foo

2008-10-28 Thread Asun Friere
On Oct 29, 7:35 am, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:

> It probably contains buggy code inside "if __name__ == '__main__': ...".

Or the code contains a run-time error?


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


Re: Triple-quoted strings hath not the Python-nature

2008-10-21 Thread Asun Friere
That should be "Triple-quoted strings HAVE not the Python-nature."
'Hath' is the archaic 3rd person SINGULAR form of 'to have,' as in "a
tripple-quoted string hath ..."
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help with Iteration

2008-10-19 Thread Asun Friere
On Oct 20, 6:10 am, Aaron Brady <[EMAIL PROTECTED]> wrote:

[snip]

> If customers are stupid, should you sell stupid software?

That's a hypothetical question with which we need never concern
ourselves.  After all, by definition customers are not stupid, but
"always right."

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


Re: OOP books?

2008-10-15 Thread Asun Friere
On Oct 16, 7:12 am, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:

[snip]

> Not a word about Python in it, 
> but:http://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-...
>
> A must-read if you want to understand OO (MHO of course).

Yes, if only to see how many of the design patterns in C++ are not
applicable to Python ;)  But seriously, the Gang of Four book is the
classic book for design patterns.  I agree that it is required
reading, but it probably requires a working knowledge of basic OO
design to get much out of it.

At a more basic level a good UML primer (such as Page-Jones'
'Fundamentals of OO Design in UML') will get you thinking about OO
Design and is worth a look.  If only to see how many of the Java-like
concepts are not applicable to Python.

Has anyone looked at, and have any opinions about, this rather
expensive tome? Goldwasser & Letcher 'Object-Oriented Programming in
Python'
http://www.amazon.com/Object-Oriented-Programming-Python-Michael-Goldwasser/dp/0136150314/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Wait or not?

2008-09-30 Thread Asun Friere
On Oct 1, 9:20 am, Eric <[EMAIL PROTECTED]> wrote:
> I've been wanting to learn Python for a while now but I can't decide
> on whether to wait for Python 3's final release and learn it or just
> go ahead and learn 2.x. Would it be hard to make the transition being
> a noob?

If you only want to learn why do you need to wait for py3.0's final
release?  Get the rc1 and start learning now.  On the other hand if
you want to write production code get 2.5 and start writing now, most
of what you'll learn between now and the final release of 3.0 will not
change.
--
http://mail.python.org/mailman/listinfo/python-list


Re: python syntax for conditional is unfortunate

2008-09-24 Thread Asun Friere
On Sep 25, 11:57 am, "Aaron \"Castironpi\" Brady"
<[EMAIL PROTECTED]> wrote:
> On Sep 24, 8:40 pm, Asun Friere <[EMAIL PROTECTED]> wrote:
> > ... I think
> > your last version ('%d thing%s' % (i, 's' if i != 1 else '')), holding
> > all variables for placeholders in the tuple, is better. It's certainly
> > more readible.
>
> It's a different answer if you have 'things is/are'.  '%d thing%s %s'%
> ( ( i, )+ ( 's', 'are' ) if i!= 1 else ( '', 'is' ) ).  Or excluding
> prepositional phrases and subordinate clauses, '%d thing%s'% ( i, 's
> are' if i!= 1 else ' is' ).

Forgive me for being dull, my caffeine levels have not yet optimal,
but I don't follow.  Both the solutions you propose do put all the
placeholder variables in the tuple.  Or are you saying it no longer
remains readible?

BTW you repeated my mistake with the first scraplet of code.

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


Re: python syntax for conditional is unfortunate

2008-09-24 Thread Asun Friere
On Sep 25, 3:16 am, Pete Forman <[EMAIL PROTECTED]> wrote:
> Asun Friere <[EMAIL PROTECTED]> writes:
>
>  > A canonical use of the conditional operator is in
>  > pluralising words, (eg. '%s dollar' % n + 's' if n!=1 else '').
>
> That fails for n == 1.  So what is best?
>

Sorry missing parantheses.  I should test, even for fragments written
out as part of a sentence. %-/

> for i in range(4):
> print '%d thing' % i + ('s' if i != 1 else '')
>

That's the corrected version of what I meant, but actually I think
your last version ('%d thing%s' % (i, 's' if i != 1 else '')), holding
all variables for placeholders in the tuple, is better. It's certainly
more readible.
--
http://mail.python.org/mailman/listinfo/python-list


Re: python syntax for conditional is unfortunate

2008-09-24 Thread Asun Friere
On Sep 25, 3:16 am, Pete Forman <[EMAIL PROTECTED]> wrote:
> Asun Friere <[EMAIL PROTECTED]> writes:
>
>  > A canonical use of the conditional operator is in
>  > pluralising words, (eg. '%s dollar' % n + 's' if n!=1 else '').
>
> That fails for n == 1.  So what is best?
>

Sorry missing parentheses.  I should test before posting, even for
code written into.

> for i in range(4):
> print '%d thing' % i + ('s' if i != 1 else '')

That is the correct version of what I meant, but your last, including
all variables for placeholders in the tuple is probably better.
--
http://mail.python.org/mailman/listinfo/python-list


Re: python syntax for conditional is unfortunate

2008-09-24 Thread Asun Friere
On Sep 24, 9:52 am, Neal Becker <[EMAIL PROTECTED]> wrote:
> In hindsight, I am disappointed with the choice of conditional syntax.  I 
> know it's too late to change.  The problem is
>
> y = some thing or other if x else something_else
>
> When scanning this my eye tends to see the first phrase and only later notice 
> that it's conditioned on x (or maybe not notice at all!).  Particularly if 
> 'some thing or other' is long or complicated.

The struggle to get a conditional operator was a long and bitter, so
in the first place we should be glad we aren't writing "y =
(conditional and [p] or [q])[0] anymore.  Since it was but grudgingly
bestowed I thought BDFL had chosen this particular syntax just to be
difficult.

However since using it for a while, I am surprised how natural it is
to use and read.  A canonical use of the conditional operator is in
pluralising words, (eg. '%s dollar' % n + 's' if n!=1 else ''). For
this and similar short uses, where the regular if statement is an
annoyance this syntax  if  else
 works nicely.  More complicated conditionals or cases
are probably better handled by an if statement. This syntax is also
probably not the best for nested conditionals.  The latter, however,
is probably feature rather than bug.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python style: exceptions vs. sys.exit()

2008-09-23 Thread Asun Friere
On Sep 24, 8:10 am, Christian Heimes <[EMAIL PROTECTED]> wrote:
> Side note:
>
> sys.exit() is just another way to write raise SystemExit. The function
> is defined as:
>

As can be seen if you were ever silly enough to call sys.exit() in
IDLE.  ;)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is 'x' an instance of a new-style class?

2008-09-16 Thread Asun Friere
On Sep 16, 8:05 pm, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
> "Gabriel Genellina" <[EMAIL PROTECTED]> writes:
> > In Python you would write isinstance(x, object).
>
> It will return True for all Python objects (except perhaps those that
> fiddle with metaclasses), not only for instances of new-style classes.
>
Unlike say isinstance(x.__class__, type) which should distinguish
between instances of new and old-style classes.
--
http://mail.python.org/mailman/listinfo/python-list


Re: lacking follow-through

2008-09-07 Thread Asun Friere
On Sep 8, 7:00 am, castironpi <[EMAIL PROTECTED]> wrote:
> I am concerned by the lack of follow-through on some responses to
> recent ideas I have described.  Do I merely have a wrong understanding
> of group policy?

[snip]

Perhaps the wrong idea of what the group is.  I would have thought
that
if one had a sufficiently developed idea and wanted to have it /
formally/
rejected, rather than merely sniped at, then writting a PEP would be
more
apposite than posting to c.l.py.

It's fine to post your not sufficiently developed ideas here merely
to
have them discussed.  But I don't know what makes you feel that you,
or
your ideas, are /entitled/ to any response at all, much less
"follow-through."
--
http://mail.python.org/mailman/listinfo/python-list


Re: no string.downer() ?

2008-08-27 Thread Asun Friere
On Aug 28, 11:34 am, John Machin <[EMAIL PROTECTED]> wrote:
> On Aug 28, 11:25 am, Asun Friere <[EMAIL PROTECTED]> wrote:
>
> > On Aug 28, 10:28 am, John Machin <[EMAIL PROTECTED]> wrote:
>
> > > Out of the possible diagnoses (trolling, incredible stupidity, feeble
> > > joke attempt) of the cause of the ensuing upper/downer question, I'm
> > > going with the third.
>
> > Never ascribe to humour that which can be adequately explained by
> > increadible stupidity!  On the other hand given up/down vs. high/low,
> > upper/downer might appear logical to someone who doesn't know that
> > "downcase" is called 'lowercase.'
>
> He knows that s.upper().swapcase() does the job, without having read
> the swapcase docs where it is screamingly obvious that lowercase is
> the antonym of uppercase???

:shrugs, Why not?  One does a dir() on one's string and sees 'upper'
and 'swapcase' (but fails to see or understand 'lower'), and takes an
educated guess at what they do.  In any case that was only a caveat to
the point I was trying to make, namely that you were probably being
too generous towards said poster.
--
http://mail.python.org/mailman/listinfo/python-list


Re: no string.downer() ?

2008-08-27 Thread Asun Friere
On Aug 28, 10:28 am, John Machin <[EMAIL PROTECTED]> wrote:

> Out of the possible diagnoses (trolling, incredible stupidity, feeble
> joke attempt) of the cause of the ensuing upper/downer question, I'm
> going with the third.

Never ascribe to humour that which can be adequately explained by
increadible stupidity!  On the other hand given up/down vs. high/low,
upper/downer might appear logical to someone who doesn't know that
"downcase" is called 'lowercase.'
--
http://mail.python.org/mailman/listinfo/python-list


Re: why in returns values for array and keys for dictionary

2008-08-25 Thread Asun Friere
On Aug 26, 10:49 am, "++imanshu" <[EMAIL PROTECTED]> wrote:
> Hi,
>
> Wouldn't it be nicer to have 'in' return values (or keys) for both
> arrays and dictionaries.
>

NO!

When you iterate over a list (or even a array) it is the members of
the list in the order they appear that is of interest.  When you
iterate over a dictionary it is the relationship between the (unique)
key and the (possibly non-unique) value that is of interest.  Moreover
the sequence of values in a dictionary lacks meaning.

What is the 'key' of a list?  It's index?  It would be cumbersome to
iterate over the range(len()) and then have to use the index
values to pull out the values from that list.  On the otherhand it
would be useless for 'in' (in the sense of for x in {...}) to return a
series of unordered values, with no way to get at the key, rather than
keys (from which the values are directly accessible).

And what would you like file_like objects, for example, to return?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python does not get environment variable when using cron.

2008-08-18 Thread Asun Friere
On Aug 18, 11:17 pm, "Shawn Milochik" <[EMAIL PROTECTED]> wrote:

>
> The easiest solution (in my opinion) is to write a bash script to
> execute your Python script, and use that bash script to add those
> environment variables.

Agreed.  Wrap it in a shell script, easier to read and grow than a
oneliner on the crontab.

> The most likely file you'll want to run is
> .bashrc in your home directory. If you're on a Mac, it's .bash_login
> instead.
>
> Example:
>
> #/usr/bin/env bash
>
> source ~/.bashrc
> path/my_script.py
>

I for one don't have $HOSTNAME defined in my .bashrc file.  I doubt
this is likely to give him much joy.

> Something like that should take care of it. If not, get creative --
> add the "env" command to your bash script and have it send the output
> to a file: env > cron_env.txt
>

Again no. The reason os.environ can't find HOSTNAME is that it is NOT
defined in the environment, if env can find it os.environ should be
able to as well.


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


Re: Python does not get environment variable when using cron.

2008-08-18 Thread Asun Friere
On Aug 19, 2:37 am, "Stephen Cattaneo" <[EMAIL PROTECTED]>
wrote:
> - What did you run in the cronjob to get back all those variables?
>
>  set; echo "-"; echo "import os; print
> os.environ" | python
>
> Cheers,
>
> S

As I should have noted from $BASH_EXECUTION_STRING.  I'd be half
dangerous if I just ... paid ... ATTENTION!

OK, the difference between using bash's builtin 'set' and '/usr/bin/
env' is that 'env' looks at ENVIRONMENT variables, whereas 'set' looks
at SHELL variables (which in bash includes HOSTNAMES).  Since shell
variables are private to the shell, 'os.environ' can only see
environment variables.

In other words if you want 'os.environ' to see a variable 'set' sees,
you have to export it from the shell to the environment, eg.
* * * * * export HOSTNAME;echo "import os;print
os.environ['HOSTNAME']" | /usr/bin/python

But note this solution depends on the particular predilections of the
bash shell.  If you are solely concerned with finding the hostname,
the more generic solution would be the one using
'socket.gethostname' (as John Machin suggested above), which
presumably calls the C library routine of the same name.

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


Re: Python does not get environment variable when using cron.

2008-08-17 Thread Asun Friere
On Aug 18, 11:15 am, "Stephen Cattaneo"
<[EMAIL PROTECTED]> wrote:
> Hello all,
>
> I am attempting to execute an automated test (written in Python) via
> cron.  I have to check the HOSTNAME variable as part of the test, oddly
> under cron the HOSTNAME environment variable is not in the os.environ
> dictionary.  I know that cron runs in a subshell that does not have all
> of the normally set environment variables.  HOSTNAME is not one of those
> variables, it is set even in cron's subshell.  Why doesn't python get
> this variable?  Is this a bug in python2.4?
>
> >From a cronjob to check environment variables in cron's shell vs
>
> python's os.environ (please excuse my lack of creativity in naming
> convention)-
>
> BASH=/bin/bash
> BASH_ARGC=()
> BASH_ARGV=()
> BASH_EXECUTION_STRING='set; echo "-"; echo "import os;
> print os.environ" | python'
> BASH_LINENO=()
> BASH_SOURCE=()
> BASH_VERSINFO=([0]="3" [1]="1" [2]="17" [3]="1" [4]="release"
> [5]="i686-redhat-linux-gnu")
> BASH_VERSION='3.1.17(1)-release'
> DIRSTACK=()
> EUID=501
> GROUPS=()
> HOME=/home/regression
> HOSTNAME=regress5
> HOSTTYPE=i686
> IFS=$' \t\n'
> LOGNAME=regression
> MACHTYPE=i686-redhat-linux-gnu
> OPTERR=1
> OPTIND=1
> OSTYPE=linux-gnu
> PATH=/usr/local/bin:/bin:/usr/bin:/home/regression/bin
> PPID=819
> PS4='+ '
> PWD=/home/regression
> PYTHONPATH=/home/regression/lib
> SHELL=/bin/bash
> SHELLOPTS=braceexpand:hashall:interactive-comments
> SHLVL=1
> TERM=xterm
> UID=501
> USER=regression
> _=/bin/bash
> -
> {'TERM': 'xterm', 'SHELL': '/bin/bash', 'SHLVL': '1', 'PYTHONPATH':
> '/home/regression/lib', 'PWD': '/home/regression', 'LOGNAME':
> 'regression', 'USER': 'regression', 'HOME': '/home/regression', 'PATH':
> '/usr/local/bin:/bin:/usr/bin:/home/regression/bin', '_':
> '/usr/bin/python'}
>
> Thanks,
>
> Steve

What did you run in the cronjob to get back all those variables?

I just ran /usr/bin/env (on a 2.6.x linux box) as a cronjob and only
got back SHELL, USER, PATH, PWD, SHLVL, HOME, LOGNAME.  This is the
same set of variables os.environ (python2.4.4) gives me when run as a
cronjob.  I tried the same thing on a bladeserver running SunOS5.9 and
got a smaller set of variables, again identical between /usr/bin/env
and os.environ.
--
http://mail.python.org/mailman/listinfo/python-list


Re: os.system question

2008-08-12 Thread Asun Friere
On Aug 13, 8:58 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Mon, 11 Aug 2008 19:28:13 -0700, Asun Friere wrote:
>
> > but if I was in a hurry to find out who I was I would be tempted still
> > to use the deprecated "os.popen('whoami').read()".
>
> Is it really deprecated? Since when? I'm using Python 2.5 and it doesn't
> raise any warnings or mention anything in the doc string.
>

I should perhaps have put 'deprecated' in quotation marks?  Note the
post I was responding to and my own stated preference.  Though I
admit, I have been trying out Popen just recently.

> The current documentation does say:
>
> "The subprocess module provides more powerful facilities for spawning new
> processes and retrieving their results; using that module is preferable
> to using this function."
>
> http://docs.python.org/lib/os-newstreams.html#os-newstreams
>
> but that's not the same as deprecating os.popen.
>

Current documentation also states:

"[The subprocess] module intends to replace several other, older
modules and functions, such as: ... [inter alia] ... os.system,
os.popen*, commands.*"

http://docs.python.org/lib/module-subprocess.html

Which is also not exactly the same thing as deprecating os.popen, but
it does sound somehwat more ominous.  One hopes the subprocess module
is not successful in realising its intentions.

I note 3.0 runs os.popen without complaint (and had thought to mention
that in my previous).  Right now I'm wondering whether I should
install the beta 2.6 to see whether Wotjek is pulling our leg or
not. :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: os.system question

2008-08-11 Thread Asun Friere
On Aug 8, 6:07 am, Mike Driscoll <[EMAIL PROTECTED]> wrote:
> On Aug 6, 8:07 pm, Kevin Walzer <[EMAIL PROTECTED]> wrote:
>
> >  >>> import os
> >  >>> foo = os.system('whoami')
> > kevin
> >  >>> print foo
> > 0
> >  >>>
>
> > The standard output of the system command 'whoami' is my login name. Yet
> > the value of the 'foo' object is '0,' not 'kevin.' How can I get the
> > value of 'kevin' associated with foo?
>
> > --
> > Kevin Walzer
> > Code by Kevinhttp://www.codebykevin.com
>
> Just an FYI, the os.system, commands, and os.popen* stuff is
> deprecated in Python 2.4+. The subprocess module is supposed to
> replace them all.
>
> See the docs for more info:http://docs.python.org/lib/module-subprocess.html
>
> I think the equivalent is subprocess.Popen with the communicate()
> method:
>
> http://docs.python.org/lib/node532.html
>
> HTH
>
> Mike

Something like this should work,

>>> from subprocess import Popen, PIPE
>>> me = Popen('whoami', stdout=PIPE, shell=True).stdout.read()

but if I was in a hurry to find out who I was I would be tempted still
to use the deprecated "os.popen('whoami').read()".
--
http://mail.python.org/mailman/listinfo/python-list


Re: Function editing with Vim throws IndentError

2008-07-22 Thread Asun Friere
On Jul 23, 7:02 am, ptn <[EMAIL PROTECTED]> wrote:
> Hi everybody,
>
> I have a weird problem.  Say I have a .py file with some functions in
> it, like this:
>
> # (...)
> def foo():
> print("bar")
>
> When I open it and add a line to one of the functions,
>
> # (...)
> def foo():
> troz = "bar"
> print(troz)
>
> I get the following traceback from the interpreter:
>
> Traceback (most recent call last):
>   File "SOMEWHERE/example.py", line ??
> troz = "bar"
>   ^
> IndentationError: unindent does not match any outer indentation
> level
>
> And so I'm forced to rewrite the function entirely just to add the new
> line.
>
> I thought that my problem was the w option from formatoptions, so I
> changed my .vimrc file to this:
>
> augroup filetype
>   autocmd BufNewFile,BufRead *.txt set filetype=human
> augroup END
> autocmd FileType human setlocal formatoptions+=ta2w
> autocmd FileType lisp,scheme,python,c,java,vim setlocal
> formatoptions-=ta2w
>
> But the problem didn't go away.

It doesn't look like those formatoptions would be called when the
filetype is python.  Or am I missing something?

> I don't think this has anything to do
> with the tabs and spaces, because I have them set up like this:
>
> set tabstop=4 shiftwidth=4 expandtab
>
> which is the standard way to handle them.

Did you actually search for tabs (/\t)?  If the file was orginally
edited without expandtabs and later expandtabs was used this is
exactly the sort of problem you would encounter.

Also you don't need to set tabstop if you in- and de-dented using
[ctrl]-[t] and [ctrl]-[d] in insert mode, and '>>' and '<<' in command
mode.

>
> The scripts I load are: qbuf, TagList, indent/python.vim and a reduced
> version of the standard python.vim
>
> Could someone provide some pointers?
>
> Thanks,
>
> Pablo Torres N.

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


Re: singletons

2008-07-16 Thread Asun Friere
On Jul 17, 8:20 am, Craig Allen <[EMAIL PROTECTED]> wrote:

> Is it pythonic?

You probably can't get anymore pythonic than something written by the
BDFL.  In describing the use of __new__ in Unifying types and
classes in Python 2.2 he gives this recipe for a Singleton.


class Singleton(object):
def __new__(cls, *args, **kwds):
it = cls.__dict__.get("__it__")
if it is not None:
return it
cls.__it__ = it = object.__new__(cls)
it.init(*args, **kwds)
return it
def init(self, *args, **kwds):
pass

You might find this a useful starting point.
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to convert '8868' to u'\u8868'

2008-06-24 Thread Asun Friere
On Jun 25, 11:30 am, CodeHunter <[EMAIL PROTECTED]> wrote:
> a = '8868'
> b = u'\u8868'
>
> I want to convert a to b
>
> who can help me ?
>
> thank you very much!

unicode(a)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does '!=' equivelent to 'is not'

2008-06-17 Thread Asun Friere
On Jun 17, 5:33 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Tue, 17 Jun 2008 02:25:42 -0300, Lie <[EMAIL PROTECTED]> escribió:

>
> > Basically 'a is b' and 'not(a is b)' is similar to 'id(a) == id(b)'
> > and 'not(id(a) == id(b))'
>
> No.
...
> ... The above statement is not. A counterexample:
>
> py> [] is []
> False
> py> id([])==id([])
> True
>
But that's not what he said, he used 'a' and 'b' which are names, not
anonymous objects.
Fairer would be,
a = [];b = []
id(a) == id(b)

Morevover, Lie wrote "id(a)==id(b)".  Since there is no need for the
anonymous object to persist following id testing, you cannot guarantee
that you are comparing an id of two objects (as referred to by 'a' and
'b').  Haven't you, in effect, tested id(a) == id(a)?  While this
might be an interesting effect, I doubt that it clarifies the
difference between equivalence and identity testing, in the way Lie's
statement in fact does.

Also in considering what equivalence means in python reference ought
to be made to the __eq__ method.  The original querant may care to
look it up.




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


Re: conventions/requirements for 'is' vs '==', 'not vs '!=', etc

2008-05-19 Thread Asun Friere
On May 20, 6:58 am, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> On 19 mai, 22:29, Luis Zarrabeitia <[EMAIL PROTECTED]> wrote:
> (snip)
>
> > The main
> > concept here: identity [usually] implies equality,
>
> I really enjoyed the "usually" disclaimer !-)

Well you have to be careful in case some smartarse comes back with a
class with something like this in it:

def __eq__ (self, other) :
if self is other : return False

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


Re: Make Python create a tuple with one element in a clean way

2008-05-11 Thread Asun Friere
On May 11, 10:54 pm, [EMAIL PROTECTED] wrote:
> To create a tuple with one element, you need to do this:
>
> >>> my_tuple = (1,)# Note the trailing comma after the value 1
> >>> type(my_tuple)
>
> 
>

You needn't at all.  You could simply do this:

>>> your_tuple = 1,

You see, it's not the parentheses that make the tuple.


> But if you do this
>
> >>> my_tuple = (1)
> >>> type(my_tuple)
>
> 
>
> you don't get a tuple.

For which the BDFL should make us eternally grateful.

> it would be clean if Python would convert anything put into ( ) to
> be a tuple

You seriously want 2*(3+4) to return (7,7)?  You call that "clean"?!

At least type(my_tuple) would always return 'tuple,' whether it was or
not. ;)

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


Re: Python MIDI in 2008

2008-05-07 Thread Asun Friere
On May 6, 7:43 pm, Max M <[EMAIL PROTECTED]> wrote:

> This is old in the sense that it has been a while since I wrote it. But
> it is virtually bug free, so nothing much is happening.
>
> The midi standard does not change so there is no real reason to
> change/upgrade it.

Maybe you should add a method somehwere that does nothing much,
increment the version number and give it a 2008 date? ;)
--
http://mail.python.org/mailman/listinfo/python-list


Re: ROUNDING???

2008-02-18 Thread Asun Friere
On Feb 19, 2:05 pm, 7stud <[EMAIL PROTECTED]> wrote:

> An integer divided by an integer produces an integer.  In computer
> programming, that's called 'integer arithmetic', and any fractional
> part of the result is chopped off(not rounded).

In case you care, the "chopped off" bit is given by the modulo
operator '%'.  So integer division x/y is really like the everyday y
goes into x, p times, remainder q, for example:

>>> 10/3, 10%3
(3, 1)

> If your arithmetic
> involves at least one float, then you will get a float as an asnwer:
>
> print 255/494
> print 255.0/494
> print (255 * 1.0)/494

or indeed "print float(255)/494"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Seemingly odd 'is' comparison.

2008-02-18 Thread Asun Friere
On Feb 19, 1:45 pm, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> "Asun Friere" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]

> | The advice not to identity test strings and numbers (since they are
> | interred in the main implementation),
>
> They may or may not be.

Obviously, and that is the problem.  The behaviour will appear
inconsistent unless one is familiar with the conditions under which
they are or are not.  So since the numbers and strings are interned
(under certain conditions), it is probably best not to identity test
them.

>
> Ditto for tuples, unless possibly when they have mutable members.
>

Which is the reason that they are never interned in CPython, no?  So I
was wrong, the categorical avoidance of identity testing is probably
_not_ sound advice with regard to tuples.

> |  But given the nature of
> | immutables, is the identity of these even potentially implementation
> | dependant (ie. they couldn't be interred could they)?
>
> The word is 'interned', not 'interred' (buried).
>

Sorry I'm a goth, so you can understand my mistake ;=

So was that a yes or no?  I mean is it even possible for the identity
behaviour of mutables to vary between implementations?  I can't see
how they can possibly be interned, but is there some other factor I'm
missing in regard to identity behaviour which could in fact vary
between implementations?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Seemingly odd 'is' comparison.

2008-02-18 Thread Asun Friere
On Feb 19, 9:44 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:

> Except for documented singletons such as modules and None, which objects
> have the same identity is platform dependent, version dependent, and even
> dependent on the execution history of your code.

The advice not to identity test strings and numbers (since they are
interred in the main implementation), or tuples, since they
potentially could be, seems sound enough.  But given the nature of
mutables, is the identity of these even potentially implementation
dependant (ie. they couldn't be interred could they)?  One might
conceivably want to know that a list into which one is about to stuff
something is the same (or perhaps not the same) list as that pointed
to by another name, which operation, hopefully, remains possible
across the range of potential implementations.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Seemingly odd 'is' comparison.

2008-02-18 Thread Asun Friere
On Feb 19, 12:27 pm, Asun Friere <[EMAIL PROTECTED]> wrote:
> But given the nature of immutables

I meant to write "given the nature of mutables" of course ... :/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Double underscores -- ugly?

2008-02-18 Thread Asun Friere

benhoyt wrote:
> Is it just me that thinks "__init__" is rather ugly?

I used to hate looking at and having the type out all those
underscores (surely two leading or one on either side would do?), but
I've gotten so used to it by now the eyes don't see and the fingers
work by themselves.

> Not to mention
> "if __name__ == '__main__': ..."?

Which ugliness is only trumped by the use of 'main' as a function name
thus:

if __name__ == '__main__' : main()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Seemingly odd 'is' comparison.

2008-02-18 Thread Asun Friere
On Feb 19, 9:44 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:

> Except for documented singletons such as modules and None, which objects
> have the same identity is platform dependent, version dependent, and even
> dependent on the execution history of your code.

The advice not to identity test strings and numbers (since they are
interred in the main implementation), or tuples, since they
potentially could be, seems sound enough.  But given the nature of
immutables, is the identity of these even potentially implementation
dependant (ie. they couldn't be interred could they)?  One might
conceivably want to know that a list into which one is about to stuff
something is the same (or perhaps not the same) list as that pointed
to by another name, which operation, hopefully, remains possible
across the range of potential implementations.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: *Oven-roasted* garlic?

2008-02-12 Thread Asun Friere
On Feb 13, 12:31 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> *Oven-roasted* garlic?  OK, that's just weird.

Not weird -- delicious!  Try doing it like this:  Take a whole knob
unpeeled dribble on some olive oil and black pepper and bake in a
medium oven for 10-15 mins.  Pull apart into individual cloves which
are pressed to squirt the now soft (and much less pungent) garlic
out.  Eat it on croutons, toast, the chicken you've just roasted at
the same time or whatever.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Removing Pubic Hair Methods

2008-01-30 Thread Asun Friere
On Jan 31, 3:13 am, Steve Holden <[EMAIL PROTECTED]> wrote:
> Wildemar Wildenburger wrote:
> > Well, you never go wrong with apply(genital(), females), do you?

Never?!

class PowerSocket () :
  def __init__ (self, plug=female, active=False) :
self.plug = plug
self.active = active

females = [p for p in powersockets if p.active and p.plug == 'female']

Ouch!!  If on the other hand 'females' is populated by instances of
(or merely includes instances of) class 'Human', I suggest you test
for female.consent somewhere in your code!

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


Re: Appropriate use of Property()

2008-01-30 Thread Asun Friere
On Jan 30, 5:03 pm, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> On 29 ene, 23:17, [EMAIL PROTECTED] wrote:
>
> > Property() can be used to rid ourselves of the extra effort of using
> > two different methods (getAttrib() setAttrib()) for access of an
> > attribute without giving direct access to the attribute, thus making
> > it more elegant. So, the outsider using my module accesses the
> > attribute with the syntax 'Object.attrib', but since this syntax looks
> > as if he is accessing the attribute (rather than through a
> > descrtiptor), should we subscribe to this syntax only when the
> > attribute is both readable and writable? i.e.,
> > if I have an attribute which I strongly believe would always be only
> > readable, should I go with the old style 'Object.getAttrib()'?
> > Would like to know different perspectives.
>

The use of accessor methods is generally eschewed in python because it
is felt that reading and writing to foo.bar.baz, for instance, results
in cleaner (more legible) code than the idiom using
foo.getBar().getBaz()/foo.setBar().setBaz().   In the culture of some
other 00 languages, directly accessing an object's method is
considered a cardinal sin because it breaks encapsulation.  The main
practical problem cited is something along this scenario:

You design an object to be used by others (objects or people), and
include an attribute x.  Without an accesor method the others would
have to look directly at the attribute (ie via y = obj.x), which is
all fine and good until you decide to change the implementation of
your object, specifically you figure that x is really primary, but
should rather be computed from a and b, so you want to remove
attribute x and add a and b.  Now with an accessor method getX(), all
you need do is change it to return a+b (or whatever), whereas if you
had relied on direct access, obviously all the other objects using
your obj.x will need to change.  Therefore it is said that other
(objects and programmers) should be isolated from implentation details
via accessor methods.

Of course in python, should that situation arise, you simply employ
property() and from the point of view of those others nothing has
changed.  In other words property() is a way of hiding implentation
details when you need to.  So we can happily access object attributes
directly even if only apparently and enjoy clean code without guilt.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Removing objects

2008-01-22 Thread Asun Friere
On Jan 23, 6:16 pm, Asun Friere <[EMAIL PROTECTED]> wrote:

> >>> x.pop(x.index(c))

Umm, of course you would simply use x.remove(c) ... force of (bad)
habit. %/



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


Re: Removing objects

2008-01-22 Thread Asun Friere
On Jan 23, 5:59 pm, [EMAIL PROTECTED] wrote:
> I am writing a game, and it must keep a list of objects. I've been
> representing this as a list, but I need an object to be able to remove
> itself. It doesn't know it's own index. If I tried to make each object
> keep track of it's own index, it would be invalidated when any object
> with a lower index was deleted.  The error was that when I called
> list.remove(self), it just removed the first thing in hte list with
> the same type as what I wanted, rather than the object I wanted. The
> objects have no identifying charachteristics, other than thier
> location in memory
>
> So my question: How do I look something up in a list by it's location
> in memory? does python even support pointers?
>
> Is there a better way?


How about adding an id attribute to your objects, which will contain a
unique identifier, override __eq__ to use that id to compare itself to
others and then simply pop off the object using
object_list.pop(object_list.index(self)).  Something like this:

>>> class Spam (object) :
def __init__ (self, id) :
self.id = id
def __eq__ (self, other) :
try :
return self.id == other.id
except AttributeError :
return False


>>>
>>> a,b,c = Spam(1), Spam(2), Spam(3)
>>> x = [a,b,c]
>>> x.pop(x.index(c))
<__main__.Spam object at 0x885e5ac>

Except your object would be telling the list to pop self of course,
and you'd need someway of insuring the uniqueness of your IDs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python beginner!

2007-11-18 Thread Asun Friere
On Nov 17, 12:41 am, Wildemar Wildenburger
<[EMAIL PROTECTED]> wrote:
> It is true that I could have been way more polite.

I don't see how. You said "please" read it.  You didn't make fun of
the poor spelling and said nothing rude.

I can't agree that the response "reeks of arrogance."  I've seen the
same thing said far more agressively.

You have to teach students as you find them.  Clearly the querent
first needs to be taught how to ask questions.  If (s)he took the time
to read the link you supplied (s)he will be rewarded by getting better
responses not only on this group but on usenet groups generally (and
probably IRL as well).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python : >>> import math doesn't work ?

2007-11-18 Thread Asun Friere
On Nov 19, 3:46 pm, windspy <[EMAIL PROTECTED]> wrote:
> use it like: x = math.sqrt (100) and math.sin(x)

alternatively import like this:

from math import sqrt, sin

... and use it like you have.

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


Re: best way of dealing with currency?

2007-10-16 Thread Asun Friere
On Oct 17, 10:56 am, Mark Shroyer <[EMAIL PROTECTED]> wrote:
> On 2007-10-16, Diez B. Roggisch <[EMAIL PROTECTED]> wrote:

> > The module decimal. But in the end, you might not be able to recreate
> > the same values as excel, due to the unknown intricacies of excel.
>
> But it can be done!  All it takes is a little dedication.  Here's a
> function that the OP might find useful, for example:
>
>   def excel_multiply(a, b):
> if a * b != 850 * 77.1:
>   return a * b
> else:
>   return 10
>
> Best of luck,
> Mark

OK joke, but it's worth noting that python's decimal behaves in the
same way as Excel given this example:
>>> from decimal import Decimal
>>> 850*Decimal('77.1')
Decimal("65535.0")
>>>

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


Re: jack audio connection kit

2007-09-25 Thread Asun Friere
On Sep 26, 4:44 am, patrick <[EMAIL PROTECTED]> wrote:
> hello everyone,
>
> is there a way to make python output audio in jack:http://jackaudio.org/
>
> jack is the best audio solution for linux, mac and lately windows. i
> found 1 project called pyjack, but the author remove the software from
> his website.
>
> that would be neat!
> pat

I suggest you email andy [at] a2hd [dot] com and ask him what happened
to PyJack.

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


Re: Sets in Python

2007-09-18 Thread Asun Friere
On Sep 19, 10:39 am, sapsi <[EMAIL PROTECTED]> wrote:

> My question is,
> 1) Why can't lists be hashed?

They are mutable.

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


Re: /dev/null as a file-like object, or logging to nothing

2007-09-10 Thread Asun Friere
On Sep 11, 10:22 am, Lawrence D'Oliveiro <[EMAIL PROTECTED]
central.gen.new_zealand> wrote:
> In message <[EMAIL PROTECTED]>, Sion Arrowsmith wrote:
>
> > Torsten Bronger  <[EMAIL PROTECTED]> wrote:
>
> > Windows has a NUL: device which behaves like /dev/null .
>
> It's not a device, it's a reserved file name. Or rather, a reserved file
> name prefix: any attempt to open a file name beginning with NUL, e.g.
> NUL.DAT, will cause your output to disappear into a black hole.

Yes Windows and its whacky error messages.  While trying to save a
Word doc as 'NUL.doc' I got this error message: "The file name
'NUL.doc' is a reserved device name."  It's no wonder some might
mistake it for a device!


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


Re: Python is overtaking Perl

2007-09-03 Thread Asun Friere
On Sep 4, 11:49 am, Erik Max Francis <[EMAIL PROTECTED]> wrote:

> Who knows?  The graph has no labeling or calibration for the y-axis, so
> it's meaningless.
>

Well yes, some calibration would make it more meaningful, but it is at
least labeled 'Search Volume.'  What's worse the calibration changes
with any search you do (try 'java programming, python programming').
In any case this is how Google describe what they are doing.

|Google Trends analyzes a portion of Google web searches to compute
how many
|searches have been done for the terms you enter, relative to the
total number
|of searches done on Google over time. We then show you a graph with
the
|results -- our search-volume graph -- plotted on a linear scale.

So I think we can at least say from the chart that searches combining
the terms 'python' and 'programming' have been falling, by some
unquantifiable amount (it don't _look_ like much!?), relative to the
number of total searches.  I think we can also say that nothing in the
chart implies that the "amount of python programers is smaller every
year."


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


Re: Python is overtaking Perl

2007-09-03 Thread Asun Friere
On Sep 4, 10:49 am, Sulsa <[EMAIL PROTECTED]> wrote:
> On Tue, 04 Sep 2007 00:32:23 -
>
> Ben <[EMAIL PROTECTED]> wrote:
> > Here are the statistics from Google Trends:
>
> >http://benyang22a.blogspot.com/2007/09/perl-vs-python.html
>
> This chart is showing that amount of python programers is smaller every
> year :(

How do you figure that?  Isn't the chart showing the frequency of
those particular terms combined as a fraction of the total search
volume on Google?

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


Re: Pythonic way of reading a textfile line by line without throwing an exception

2007-08-28 Thread Asun Friere
On Aug 29, 9:49 am, "Deivys Ramirez" <[EMAIL PROTECTED]> wrote:

> What's the "pythonic" way of reading a text file, line by line,
> without throwing an exception when there's nothing to be read?
>
> I've been trying to map my while(!eof(fp)) mindset to the file object
> Python gives me when I call open() but have had no good results.

As the previous posts have indicated the idiomatic (and highly
readable) way to read a file is simply to iterate across it.  Just in
case you are ever in the position of having to use .readline()
directly, you might want to note that this method returns empty lines
as '\n' (go figure) and the EOF simply as ''.  So you test of EOF
using 'if not line :' rather than anything like 'if eof :'
Historically, ie. before file objects were iterables, you would have
written something like this:

fobj = open('foo.txt')
while 1 :
line = fobj.readline()
if not line :
break
#do stuff to line
fobj.close()

Obviously iterating 'for line in fobj : ' is neater.

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


Re: Newbee Question

2007-08-21 Thread Asun Friere
On Aug 21, 5:51 pm, Asun Friere <[EMAIL PROTECTED]> wrote:
> On Aug 21, 5:41 pm, Asun Friere <[EMAIL PROTECTED]> wrote:> over = 
> Decimal('1.40)
>
> oops, that should of course be:
> over = Decimal('1.40')

oh boy ... and it should also be
normal = Decimal('0.40')

I really need to test before posting ...

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


Re: Newbee Question

2007-08-21 Thread Asun Friere
On Aug 21, 5:41 pm, Asun Friere <[EMAIL PROTECTED]> wrote:
> over = Decimal('1.40)
oops, that should of course be:
over = Decimal('1.40')

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


Re: Newbee Question

2007-08-21 Thread Asun Friere
Oh well since a few solutions have already been posted I thought I
might add another, just so you at the very least you have to do some
work making up your mind which one to choose.  Using an incremental
approach just to be different ...

from decimal import Decimal

normal = Decimal('0.04')
over = Decimal('1.40)

def calcStopPay (stops) :
pay = Decimal('0.00')
while stops :
incr = normal if stops < 23 else over
pay += incr
stops -= 1
return pay

#testing:
for x in range(50) :
print "Stop pay for %s stops: $%s" % (x, calcStopPay(x))

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


Re: str().join() isn't working

2007-08-20 Thread Asun Friere
On Aug 21, 4:34 am, [EMAIL PROTECTED] wrote:
> to concatenate 2 lists to each other before it does the join, ... is
> impossible in Python. The "+" operator is only for addition and for
> two or more strings.

Really?

>>> [1,2,3] + [4,5,6]
[1, 2, 3, 4, 5, 6]

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


Re: Base class for file-like objects? (a.k.a "Stream" in Java)

2007-07-24 Thread Asun Friere
On Jul 25, 8:51 am, Boris Dušek <[EMAIL PROTECTED]> wrote:

> In Python, I found that "file" objects exist. While specifying
> argument types in Python is not possible as in Java, it is possible to
> check whether an object is an instance of some class and that's what I
> need - I need to check if an argument is a "file"-like object, and if
> yes, behave accordingly, if not, treat the argument as string with
> URL.
>
> But I am afraid there is no such a base class - I tried the following:
>

Yup you are right.  Look.
>>> type(g).mro()
[, ]
>>> type(f).mro()
[, ]

"File-like object" refers the the behaviour of the object, not it's
inheritance.  Python is an equal opportunity employer, we don't ask
and object what race it is, we simply ask "can you do the job?"  This
is known colloquially as "duck-typing."  In other words Python has
'polymorphism by interface,' in contradistinction to Java's
'polymorphism by implementation.'  Until you understand this you will
be trying to write Java in Python, and you will not have much joy.

> P.S.: The code should finally look in esence something like this:
>
> if isinstance(f, file):
>pass
> elif isinstance(f, string):
>f = urllib.urlopen(f)
> else:
>raise "..."
> process_stream(f)

Because of duck-typing, you should almost never use the isintance()
(or type(), hasattr(), or any others that don't immediately come to
mind ...) in actual code. It (usually) breaks Python's polymorphism!
If you find these methods popping up in your code it strongly
indicates that you should be using a try/except statement, if not a
complete change of your code's logic.  Search for LBYL (look before
you leap) vs EAFP (easier to ask forgiveness than permission) for a
full explanation.

I'm not sure why you would ever be sending a file object to urlopen
(or is the test isinstance(f, file) supposed to test for an already
opened url?), but you final code should actually look more like
something along these lines:

try :
  f = urlopen(f)
except AttributeError :
  pass

This is not as elegant as it could be, as it will pass not only on
open files (or urls), but on any type that lacks the .strip method
(ie. it doesn't account for your else condition).  You'd probably have
to catch an exception later when you try to use what should be an open
url, or rewrite your code not to get in this position in the first
place.  But however you refactor your code, it is advisable to
concentrate on what an object can do (and catch an exception where it
fails to perform), rather on the type of the object.

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

Re: In a dynamic language, why % operator asks user for type info?

2007-07-17 Thread Asun Friere
On Jul 17, 5:38 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:

> indeed anything which has an __int__ method may be
> passed to the %d formatter:

Anything?! Sorry to be persnickety here, but what about this:

class C :
  def __int__ (self) : pass

'%d' % C()

or this:

def foo (val) : return val
foo.__int__ = lambda x=42 : int(x)

'%d' % foo('spam')

OK, they can be passed ...

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


Re: In a dynamic language, why % operator asks user for type info?

2007-07-16 Thread Asun Friere
In practice the different placeholders give you a handle to achieve
different formatting effects.

Compare for example:

for x in range(15) :
  print '%02d' % x

against:

for x in range(15) :
  print '%02s' % x
  #the '0' in this case being redundant

Or again:

from math import pi
print '%.4f' % pi
print '%.4s' % pi
#if that last seems silly consider
print '%.4s % 'hello world'

Given that there already exists an established (and documented) printf
convention, one could argue that overloading (or even augmenting) the
established placeholders is not the best option in this case.

>If the above is the case, we could've avoided all those exceptions
>that happen when a %d is specified but say a string is passed.

Generally I prefer handling exceptions to avoiding them.

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


Re: pattern match !

2007-07-15 Thread Asun Friere
On Jul 11, 9:29 pm, Helmut Jarausch <[EMAIL PROTECTED]>
wrote:
> import re
> P=re.compile(r'(\w+(?:[-.]\d+)+)-RHEL3-Linux\.RPM')
> S="hpsmh-1.1.1.2-0-RHEL3-Linux.RPM"
> PO= P.match(S)
> if  PO :
>print PO.group(1)

Isn't a regexp overkill here when this will do:

head = filename[:filename.index('-RHEL3')]

Of course if you need to make it more generic (as in Jay's solution
below), re is the way to go.

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


Re: pattern match !

2007-07-10 Thread Asun Friere
On Jul 11, 1:40 pm, [EMAIL PROTECTED] wrote:
> Extract the application name with version from an RPM string like
> hpsmh-1.1.1.2-0-RHEL3-Linux.RPM, i require to extract hpsmh-1.1.1.2-0
> from above string. Sometimes the RPM string may be hpsmh-1.1.1.2-RHEL3-
> Linux.RPM.

Now that list-like splicing and indexing works on strings, why not
just splice the string, using .index to locate '-RHEL'?

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


Re: Comparing modified elements in Sets

2007-07-10 Thread Asun Friere
On Jul 10, 5:57 am, [EMAIL PROTECTED] wrote:
> I'd like to be able to compare set 1 with set 2 and have it match
> filename1 and filename3, or compare set 1 with 3 and get back
> filename1, filename2.  etc.
>
> Is there a way for me to do this inside the compare function, rather
> than having to make duplicate copies of each set?

Is there a will?
Inevitably there is a way! Whether you should take it is another
question entirely. ;)

Assuming by 'compare' function you mean such methods as 'difference,'
'symetric_difference', 'intersection' and the like... here's a nasty
little hack (using the old-school Set from sets.py)  It's not to spec
(you get the tails back in the result, but that's easily fixed), and
it only implements a replacement method for 'difference' (called
'tailess_difference).

I apologise if the google groups mailer kludges the indentation ...
-
from sets import Set
from itertools import ifilterfalse
from os.path import splitext

class BodgySet (Set) :

def tailess_difference (self, other) :
"""Return, as a new BodgySet, the difference of two
sets, where element identity ignores all characters
from the last stop (period).

NOTE: As currently implemented all elements of said
sets must be strings (fix this in self.has_key)!!!

"""
assert other.__class__ is self.__class__
result = self.__class__()
data = result._data
value = True
for elt in ifilterfalse(other.has_key, self) :
data[elt] = value
return result

def has_key (self, target) :
thead, ttail = splitext(target)
for key in self._data.keys() :
khead, ktail = splitext(key)
if thead == khead :
return True
-

Using this hacked set:
>>> a = BodgySet(['a1.txt', 'a2.txt'])
>>> b = BodgySet(['a1.xml', 'a2.xml', 'a3.xml'])
>>> b.tailess_difference(a)
BodgySet(['a3.xml'])

Is that the kind of thing you had in mind?

While it can be done, I would prefer to make copies of the sets, with
a cast list comprehension something like:  set([os.path.splitext(x)[0]
for x in orig_set]).  Much better readibility and probably greater
efficiency (I haven't bothered timing or dissing it mind).

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


Re: Unable to strip \n characters

2007-05-23 Thread Asun Friere
On May 22, 6:37 am, aiwarrior <[EMAIL PROTECTED]> wrote:
> On May 21, 7:05 am, Asun Friere <[EMAIL PROTECTED]> wrote:
>
> > On May 20, 10:49 pm, Michael Bentley <[EMAIL PROTECTED]>
> > wrote:
>
> > > On May 20, 2007, at 7:41 AM, Michael Bentley wrote:
>
> > > > (upload.strip())
>
> > > Oops: (upload.strip(),) or upload.strip()
>
> > Superfluous though the braces around your original were, it should
> > still run ...
> > ie. (a) == a
>
> When you mean superfluous you mean it makes a diffrence in run-time or
> just code style?


Hmm I thought I already answered, but it hasn't turned up so ...

It is superfluous in both senses, ie it will (v. marginally) affect
run-time performance, and it is generally considered good coding style
not to include parentheses where they are not needed, (though one
should not be absolute about this, there may be cases where
superfluous parentheses greatly clarify the meaning of some code).

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


Re: howto check does module 'asdf' exist? (is available for import)

2007-05-22 Thread Asun Friere
On May 21, 11:17 pm, dmitrey <[EMAIL PROTECTED]> wrote:
> howto check does module 'asdf' exist (is available for import) or no?
try :
  import asdf
  del asdf
except ImportError :
  print "module asdf not available"
else :
  print "module asdf available for loading"

You can generalise this, but at the expense of a couple of exec
statements:
def is_module_available (module) :
try :
exec('import %s' % module)
exec('del %s' % module)
except ImportError :
return False
else :
return True

> (without try/cache of course)
Oops sorry, you wanted it done in some non-obvious way!  Why?!

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


Re: howto check does module 'asdf' exist? (is available for import)

2007-05-21 Thread Asun Friere
On May 21, 11:17 pm, dmitrey <[EMAIL PROTECTED]> wrote:
> howto check does module 'asdf' exist (is available for import) or no?

try :
  import asdf
  del asdf
except ImportError :
  #do stuff ...

> (without try/cache of course)

Oops sorry, you didn't want it the obvious way ... but why ever not?



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


Re: Types in Python (was: managed lists?)

2007-05-21 Thread Asun Friere
On May 22, 10:28 am, Ben Finney <[EMAIL PROTECTED]>
wrote:
> "Jorgen Bodde" <[EMAIL PROTECTED]> writes:
> > Right now i have a list in a class that I export as a member
> > variable to the outside world, it is a standard list (e.g. [] ) but
> > I wish to have a stronger type checking when adding objects, that
> > only some objects are allowed and others are not.
>
> This is a poor idiom in Python. The object system allows powerful
> polymorphism: the only thing that your application should be checking
> is if the objects *can be used* in a particular way, not that they
> belong to a specific subset of the type hierarchy.

And this very succintly sums up the nature of Python's polymorphism
by interface (duck-typing).  An understanding of this is central to
groking the way typing and OO are done in python.

"Jorgen Bodde" <[EMAIL PROTECTED]> writes:
> I solved it now, by using isinstance() and giving the class name as
> argument to the list

There may be some situations in which testing for class (or
inheritance) are
appropriate, however in the vast majority of cases doing so is a
mistake.  The
object should itself know what to do in any given situation (or throw
an
exception if it doesn't).  Similarly your program should be responding
to
exceptions rather than checking before hand whether its OK to go on.

Instead of reaching for 'isinstance()' you should probably be using
'try : ... except: ...'

> and it sometimes frustates me to no end that a wrongly given
> argument explodes somewhere deep inside my application without
> giving any clue why it blew up in the first place..

If by 'explode' you mean spitting out feedback (as opposed to
hanging),
you should find at least a few clues.  At the very least, you now know
one of the exceptions your code will need to handle.

Asun

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


Re: Types in Python (was: managed lists?)

2007-05-21 Thread Asun Friere
On May 22, 10:28 am, Ben Finney <[EMAIL PROTECTED]>
wrote:
> "Jorgen Bodde" <[EMAIL PROTECTED]> writes:
> > Right now i have a list in a class that I export as a member
> > variable to the outside world, it is a standard list (e.g. [] ) but
> > I wish to have a stronger type checking when adding objects, that
> > only some objects are allowed and others are not.
>
> This is a poor idiom in Python. The object system allows powerful
> polymorphism: the only thing that your application should be checking
> is if the objects *can be used* in a particular way, not that they
> belong to a specific subset of the type hierarchy.

And this very succintly sums up the nature of Python's polymorphism
by interface (duck-typing).  An understanding of this is central to
groking the way typing and OO are done in python.

"Jorgen Bodde" <[EMAIL PROTECTED]> writes:
> I solved it now, by using isinstance() and giving the class name as
> argument to the list

There may be some situations in which testing for class (or
inheritance) are
appropriate, however in the vast majority of cases doing so is a
mistake.  The
object should itself know what to do in any given situation (or throw
an
exception if it doesn't).  Similarly your program should be responding
to
exceptions rather than checking before hand whether its OK to go on.

Instead of reaching for 'isinstance()' you should probably be using
'try : ... except: ...'

> and it sometimes frustates me to no end that a wrongly given
> argument explodes somewhere deep inside my application without
> giving any clue why it blew up in the first place..

If by 'explode' you mean spitting out feedback (as opposed to
hanging),
you should find at least a few clues.  At the very least, you now know
one of the exceptions your code will need to handle.

Asun

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


Re: Unable to strip \n characters

2007-05-20 Thread Asun Friere
On May 20, 10:49 pm, Michael Bentley <[EMAIL PROTECTED]>
wrote:
> On May 20, 2007, at 7:41 AM, Michael Bentley wrote:
>
> > (upload.strip())
>
> Oops: (upload.strip(),) or upload.strip()

Superfluous though the braces around your original were, it should
still run ...
ie. (a) == a

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


Re: How do I count the number of spaces at the left end of a string?

2007-05-16 Thread Asun Friere
On May 17, 8:18 am, Steven Howe <[EMAIL PROTECTED]> wrote:
> walterbyrd wrote:
> > I don't know exactly what the first non-space character is. I know the
> > first non-space character will be  * or an alphanumeric character.
>
> using builtin function rindex

But only if there is a guarantee that are spaces nowhere else in the
string:

a = 'abc'
print a.rindex(' ') + 1
=> 4

Good, but ...

b = 'ab c'
b.rindex(' ') + 1
=> 7
Ouch!

The difference method suggested by Daniel Nogradi, seems the most
obvious way.

len(b) - len(b.lstrip())
=> 4

Asun

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


Re: How do I tell the difference between the end of a text file, and an empty line in a text file?

2007-05-16 Thread Asun Friere
On May 17, 7:47 am, walterbyrd <[EMAIL PROTECTED]> wrote:
> Python's lack of an EOF character is giving me a hard time.

The difference is simply that an empty line contains a '\n' while EOF
does not.  If you strip() your line before testing you will have
trouble.  But the minimal cases you post (properly indented and with
the missing ':' in place), should work (they just won't produce any
output). Repairing the first , I'm using dots (aka stops, periods) for
spaces here to stop the code getting munged :

line = fobj.readline()
while line :
print line.strip()
line = fobj.realine()

This does work look at this output (and note the empty lines):
line with stuff
line with more stuff

line after the empty line and before another

last line

In python it is more ideomatic to write this general kind of loop with
a break statement, thus:

while True :
line = fobj.readline()
if not line : break
print line.strip()

However since file has for a long time been an iterable the easiest
and most readible way to write it is this:

for line in fobj :
print line.strip()

Asun

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


  1   2   >