Re: lower-case names for builtin types

2011-10-03 Thread rantingrick
On Oct 1, 10:41 pm, Eric Snow ericsnowcurren...@gmail.com wrote:
 Anyone know the story behind the lower-case names for the
 non-exception built-in types (like list and type)?  I am guessing that
 they were originally factory functions that, at some point, graduated
 to full types; and the names were kept lower-case for backward
 compatibility.

Or it could be that they wanted to hoard all the good generic variable
names!

 However, if we were to consider making a change for Python 4, I am not
 sure how I feel about Int(5) over int(5).  Maybe it would be
 Integer(5).

Yes!

Some folks get all huffy about this subject because they get SO
attached to built in functions. What's so weird about calling a
function that THEN calls a constructor as opposed to just calling the
constructor directly? Seems like unnecessary overhead to me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Chaos Theory [was Re: Benefit and belief]

2011-10-03 Thread rantingrick
On Oct 2, 4:43 pm, Steven D'Aprano steve
+comp.lang.pyt...@pearwood.info wrote:

 In all cases, we can be sure that the contradiction between the pair of
 statements are genuine contradictions and not mere apparent
 contradictions caused by narrow perspective or incomplete or erroneous
 knowledge.

Observer: Why is it that Clark Kent and Superman are never in the same
place at the same time?
ComicFanboy: Because Clark Kent IS Kal-El's secret identity duh!
PuesdoWiseObserver: Wait a minute fanboy, they ARE in the same place
at the same time since Clark Kent IS really Superman. Ha, i'm smart.
TrueWiseObserver: Wrong pseudo. Superman will ALWAYS be superman even
if he wears a dress and stilettos. Clark Kent is just an assumed
identity of Superman.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible to create C-style main function in Python? (for teaching purposes)

2011-10-03 Thread rantingrick
On Oct 3, 2:14 pm, Dave Angel da...@ieee.org wrote:

 Like it or not, there are plenty of globals already there, one of them
 being __name__ .  All the built-ins are effectively global, and so
   is any function they define at top-level.

I keep wondering if that was another PyWart? I believe (and hindsight
is 20-20) that all the built-in modules should have been protected by
a top-level namespace. Something succicent, something like py...

from py.archive import zipfile, tarfile
from py.gui import Tkinter
from py.markup import HTMLParser

...and voila, no more clashes with user defined modules!


 Likewise any top-level
 class, and any symbols imported with import or with from/import.  So I
 consider it impractical for the language to do something that
 self-discipline is required for.

Also for scoping.

py count = 0
py def foo():
... global.count += 1
py print count
1

Why? Well because many times i find myself wondering if this or that
variable is local or global -- and when i say global i am speaking
of module scope! The globalDOT cures the ill.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question: How to Prevent Tkinter Menu from Taking Keyboard Focus

2011-10-03 Thread rantingrick
On Oct 3, 2:55 pm, galyle gal...@gmail.com wrote:
 Hello, I'm trying to build a menu which provides suggestions to a user
 based on input to an entry.  I have done something like this before
 using Tcl/Tk, so I expected that it would work without much difficulty
 with Tkinter.  I was wrong.


Why not just use the Tix.ComboBox instead? I believe it's editable.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Chaos Theory [was Re: Benefit and belief]

2011-10-03 Thread rantingrick
On Oct 3, 11:27 am, Chris Angelico ros...@gmail.com wrote:

 PhysicsExpert: Super-speed wouldn't work, the acceleration required to
 achieve it would burn up his surroundings!

For some definition of super-speed i suppose. Since we're bouncing
around the relatives here we need to consider this one also - Super
Speed to a tortoise will be super-slow, say for example, compared to
the air-speed velocity of an unladen swallow.

 Your point?

Reductio ad Absurdum
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replacing spreadsheets by Python and the browser

2011-10-02 Thread rantingrick
On Oct 2, 12:36 pm, markolopa marko.lopa...@gmail.com wrote:

 Examples of information I would store in such a tree/table system
 (which are now in spreasheets):
 - My dvd, avi collection: The tree would be the directory tree of the
 file system where I store my movies. For each directory containing the
 avis or the dvds there would be a table with one movie by row and
 several editable columns: the file name, the genre, the year, whether
 I have seen it or not, comments, etc.
 . The same thing for mp3.
 - My family budget. The tree would be the account tree, the rows in
 the table would be the deposits and withdrwals. This is actually my
 most important need. I don't find gnucash flexible enough for my
 needs.  Beancount (http://furius.ca/beancount/) has a great html
 output, but I would like to use the browser also for input.

Is there any reason why you could not use the advanced widgets in
WxPython? You never said whether this MUST BE a web application. If
GUI is okay then check out wxListCtrl and wxTreeCtrl. All you need to
do is write a little control code and voila.

http://www.wxpython.org/onlinedocs.php
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Benefit and belief

2011-09-30 Thread rantingrick
On Sep 29, 10:05 pm, alex23 wuwe...@gmail.com wrote:
 On Sep 30, 9:37 am, MRAB pyt...@mrabarnett.plus.com wrote:

  alex23:
  And like the Bible, the Zen was created by humans as a joke. If you're
  taking it too seriously, that's your problem.

 Strangely, calling the bible self-contradictory wasn't seen as
 inflammatory...

For the same reason that telling the truth is not slander. The fact is
that the Bible IS contradictory with itself. However, your opinion
unlike my facts, were full of vile hatred. Nice try attempting to
shift the mob against me.



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


Re: Suggested coding style

2011-09-30 Thread rantingrick
On Sep 29, 11:49 pm, Ian Kelly ian.g.ke...@gmail.com wrote:
 Nope, that doesn't work.

  {0:010}.format(-1234)

 '0-1234'

 The whole point of zfill is that it handles signs correctly.

py {0:-010d}.format(-1234)
'-01234'

My point was: Use the {char}{repeat}d format for integers and the
{char}{||=}{repeat} for strings. Problem solved. No more need for
zfill.

py {0:010}.format(-1234)
'0-1234'

What result would you expect from that string argument? I think it
behaves as anyone would expect. If you have a str and you want it
interpreted as a negative integer then cast it.

py {0:010d}.format(int(-1234))
'-01234'

If you would like for the spec to handle the case of integers and
strings transparently then you need to lobby to have the API changed.
Maybe they could add a !i like the !s and !r which would be explicit.
However, i don't think implicit coercion of strings to integers is a
good idea. Using the int function or !i removes and ambiguities.

For me, the spec works just fine as is.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggested coding style

2011-09-30 Thread rantingrick
Note: I am quoting Passiday to get this thread back on subject
however my reply is for alex23 the philosopher

On Sep 29, 9:50 pm, alex23 wuwe...@gmail.com wrote:
 On Sep 29, 10:23 pm, rantingrick rantingr...@gmail.com wrote:

  What is so bad about breaking code in obscure places?

 Try coding in PHP across minor release versions and see how you feel
 about deprecating core functions on a whim.

I never said we should remove it now, i said we should deprecate it
now.

  We changed print
  to a function which broke just about every piece of code every written
  in this language.

 In a well declared _break_ with backwards compatibility. Not on a whim
 between minor releases.

Please Google deprecate.

  What is so bad then about breaking some very obscure code?

 Because while you say some very obscure code, what you really mean
 is code that isn't mine.

Well alex i can't see a mob approaching with pitchforks because we
deprecate a misplaced and rarely used functionality of the stdlib.

 As you have no access
 to the inner states of _any_ of the people you regularly condemn here
 with your hypocritical attacks, I've no idea why you consider yourself
 to be an expert on their desires and opinions.

Well alex, like yourself, i hold expertise in many fields BESIDES
programming. One of which being psychology.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Benefit and belief

2011-09-30 Thread rantingrick
On Sep 30, 11:36 am, Westley Martínez aniko...@gmail.com wrote:
 On Fri, Sep 30, 2011 at 09:22:59AM -0700, rusi wrote:
  On Sep 30, 8:58�pm, Neil Cerutti ne...@norwich.edu wrote:
   On 2011-09-30, DevPlayer devpla...@gmail.com wrote:

I still assert that contradiction is caused by narrow perspective.

By that I mean: just because an objects scope may not see a certain
condition, doesn't mean that condition is non-existant.

I also propose that just because something seems to contradict doesn't
mean it is false. Take for instance:

Look out your window. Is it daylight or night time? You may say
it is daylight or you may say it is night time. I would
disagree that only one of those conditions are true. Both
conditions are true. Always. It is only day (or night) for YOU.
But the opposite DOES in fact exist on the other side of the
world at the same time.

I call this Duality of Nature (and I believe there was some
religion somewhere in some time that has the same notion,
Budism I think but I could be mistaken). I see such
contradictions in what appears to be most truths.

   You are not alone. Many ancient philosophers, fathers of
   religious and scientific thought, thought the same.

   They thought that contradictory qualities could exist in objects
   simultaneously. For example, they thought that a cat was both big
   and small, because it was big compared to a mouse and small
   compared to a house. They didn't notice that big and small were
   not poperties of the cat, at all but were instead statements
   about how a cat relates to another object.

   When you say, It is night, you are making an assertion about a
   position on the surface of the earth and its relationship to the
   sun.

   If you are not discussing a specific a position on the Earth,
   then you cannot make a meaningful assertion about night or day at
   all. Night and Day are not qualities of the entire Earth, but
   only of positions on the Earth.

  But just imagine that we were all pre-galiliean savages -- knowing
  nothing about the roundness of the earth, the earth going round and so
  on and somehow you and I get on the phone and we start arguing:
  Rusi: Its 9:30 pm
  Neil: No its 12 noon

  How many cases are there?
  We both may be right, I may be wrong (my watch may have stopped) or we
  both etc

  ie conflicting data may get resolved within a larger world view (which
  is what devplayer is probably saying).

  Until then it is wiser to assume that that larger world view exists
  (and I dont yet know it)
  than to assume that since I dont know it it does not exist.

  For me (admittedly an oriental) such agnosticism (literally I-do-not-
  know-ness) is as much a foundation for true religiosity as effective
  science

 I.e. humility?

@DevPlayer, rusi, Neil, Wes, and group

Yes, there are two views of reality; that of the absolute and that of
the relative. Both are true. It is always daytime and nighttime
simultaneously; if you look at things from a global perspective.

However, the true nature of daytime vs nighttime is purely a
relative observation. The fact that both exist does not falsify the
validity of the relative view. Recognizing the paradox is important
and proves you are not confined to your own selfish view points and
are in fact an intelligent being.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggested coding style

2011-09-29 Thread rantingrick
On Sep 29, 5:37 am, Passiday passi...@gmail.com wrote:

 Here's a summary of what I take from this longwinded thread:
 Read the Zen of Pthon for some fun:http://www.python.org/dev/peps/pep-0020
 Read the PEP-8 for some good 
 guidelines:http://www.python.org/dev/peps/pep-0008

That's the point of all this, yes. You see, around here, once the
point is made there is an unwritten rule that the thread must then
descend into chaos. However, it seems you may have brought this
train wreck back to reality below... whether the trolls will allow
that happen remains to be seen...?

 My topic was Suggested coding style because I hoped
 there is some common understanding which of the ancient
 methods/functions are so not where they should be that the
 use of them should be depreciated.

I agree. Whilst zfill is useful, and probably should be a part of the
stlib somewhere, the string module is no place for it. The only way
zfill WOULD work as a string method is if it were changed to accept a
user defined fill char. Even then i don't like it as a string method;
too specific!

A specific method for padding a string with ONLY zeros is ludicrous
and exposes the narrow mindedness of the creator. The only thing worse
than zfill as a string method is making zfill into built-in
function! The ONLY proper place for zfill is as an option in the
str.format() method.

py {0:zf10}.format(1234) - 001234

When are they going to see that I am the best API designer this
community has ever had the privilege to work with! GvR should be
texting me every night in hopes that some of my API genius will rub
off on him.

 I can fully understand
 that when the language evolves, it might implement some
 ugly methods. Perhaps it was some quick itching need to
 format some numbers that drove some antique Python
 programmer so mad that he decided this belongs to the
 string class, instead of some number/date/string
 formatting class that attempts to build on existing well
 established standards. And so, the str.zfill() was born.

zfills foster home placement is akin to the missing Path object we
still don't have. Both are a result of poor planning. Now zfill is
like some red headed step child that nobody wants, but nobody has the
balls to return the abortion to it's rightful place.

 But I'd expect that there exists some leadership who are
 brave enough to admit some bad decisions and lead the
 people by announcing that using certain methods is bad
 style.

Ha! I would not hold my breath waiting for leadership to admit wrong
doings; these people think they are beyond reproach.

 No need to take them out of the implementation,
 that might unnecessary break some code in obscure places.

What is so bad about breaking code in obscure places? We changed print
to a function which broke just about every piece of code every written
in this language. (BTW, print should ALWAYS have been a function!)
What is so bad then about breaking some very obscure code? We could
always have a lengthy deprecation period.

 However, guiding programmers for better coding practice
 and avoid ugly bloating of nice scripting language should
 be considered a holy (please don't rant on use of this
 word) mission.

I agree. I think you'll agree also with me in the fact that Mr Van
Rossum has created the cleanest, most simplistically elegant, and no
nonsense language this world has ever seen. However. He is not immune
to the wicked influence of a few high ranking people within this
community who have hidden agendas and want to mutate Python into a
clone of some other nasty languages.

I believe GvR had a mid-dev-crisis and realized the err of his ways.
He attempted to turn back the clock with Python 3000, HOWEVER he did
not go far enough! Much more cleanup is in order to get this language
back on track to what it should be, and COULD be!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggested coding style

2011-09-29 Thread rantingrick
On Sep 29, 7:23 am, rantingrick rantingr...@gmail.com wrote:

 A specific method for padding a string with ONLY zeros is ludicrous
 and exposes the narrow mindedness of the creator. The only thing worse
 than zfill as a string method is making zfill into built-in
 function! The ONLY proper place for zfill is as an option in the
 str.format() method.

 py {0:zf10}.format(1234) - 001234


If something like zfill where to be included as a string method, it
should be more general like this:

class String:
def pad(self, char, count, side='left') = str

py .pad(0, 10)
'001234'

However the same can be accomplished with:

py '{0}1234'.format(0*10)
'001234'

py 0*10+'1234'
'001234'

Seems like pollution either way you go. Best to just let the
programmer handle it. Python IS NOT a 100% OOP language (and for good
reason!) so we don't need methods to scratch every little itch -- and
this itch seems to have originated in the nether regions instead of
the Netherlands.


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


Re: Suggested coding style

2011-09-29 Thread rantingrick
On Sep 29, 5:12 pm, Ian Kelly ian.g.ke...@gmail.com wrote:
 On Thu, Sep 29, 2011 at 6:23 AM, rantingrick rantingr...@gmail.com wrote:
  A specific method for padding a string with ONLY zeros is ludicrous
  and exposes the narrow mindedness of the creator. The only thing worse
  than zfill as a string method is making zfill into built-in
  function! The ONLY proper place for zfill is as an option in the
  str.format() method.

  py {0:zf10}.format(1234) - 001234

 Agree that zfill seems to be redundant with str.format, although your
 suggested syntax is atrocious, especially since a syntax already
 exists that fits better in the already-complicated format specifier
 syntax.

It's interesting that you find the format specifier complicated. I
will admit that upon first glance i lamented the new format method
spec and attempted to cling to the old string interpolation crap.
However, as you use the new format method you will come to appreciate
it. It's an adult beverage with an acquired taste. ;-)

One thing that may help format noobs is to look at the spec as two
parts; the part before the colon and the part after the colon. If you
break it down in this manner the meaning starts to shine through. I
will agree, it is a lot of cryptic info squeezed into a small space
HOWEVER you would no want a verbose format specification.

But i wholeheartedly agree with you points and i would say the zfill
method has no future uses in the stdlib except for historical reasons.
We should deprecate it now.


 {0:=010d}.format(1234) - 001234

 There are a couple of warts with the existing implementation, however:

 1) str.zfill() operates on strings; the .format() syntax operates on
 numeric types.  I would suggest that the = fill alignment in format
 specifiers should be extended to do the same thing as zfill when given
 a string.

EXACTLY!

PS: Has anyone noticed all the off topic chatter about religion and
feelings? Since the main subject of this thread is about zfill i can't
help but wonder if the minions where sent out to present a distraction
with scripted pseudo arguments. Just an observation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggested coding style

2011-09-29 Thread rantingrick
On Sep 29, 6:07 pm, Devin Jeanpierre jeanpierr...@gmail.com wrote:
  However, as you use the new format method you will come to appreciate
  it. It's an adult beverage with an acquired taste. ;-)

 Yeah. It's a much more difficult to read thing, but once you learn how
 to write it it flows faster.

 Of course, I never managed to learn how to write it...

A good way to start out is to just use the positional arguments.

py name = Bob

py Hello my name is {0}.format(name)
Hello my name is Bob

py Hello my name is {name}.format(name=name)
Hello my name is Bob

py Hello my name is {0}. My named spelled backwards is:
{0}.format(name)
Hello my name is Bob. My named spelled backwards is: Bob

py A small fry cost {0:0.2f}.format(1.666)
A small fry cost 1.67

py A small car cost {0:,.2f}.format(11666.)
A small car cost 11,666.67

# Python 2.7+ you can omit the index.
py {} = {}.format(value,2)
value = 2

Start with the small stuff and then diversify! You'll be glad you made
the change.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggested coding style

2011-09-29 Thread rantingrick
On Sep 29, 5:12 pm, Ian Kelly ian.g.ke...@gmail.com wrote:
 On Thu, Sep 29, 2011 at 6:23 AM, rantingrick rantingr...@gmail.com wrote:
  A specific method for padding a string with ONLY zeros is ludicrous
  and exposes the narrow mindedness of the creator. The only thing worse
  than zfill as a string method is making zfill into built-in
  function! The ONLY proper place for zfill is as an option in the
  str.format() method.

  py {0:zf10}.format(1234) - 001234

 Agree that zfill seems to be redundant with str.format, although your
 suggested syntax is atrocious, especially since a syntax already
 exists that fits better in the already-complicated format specifier
 syntax.

 {0:=010d}.format(1234) - 001234

 There are a couple of warts with the existing implementation, however:

 1) str.zfill() operates on strings; the .format() syntax operates on
 numeric types.  I would suggest that the = fill alignment in format
 specifiers should be extended to do the same thing as zfill when given
 a string.

Ah ha! Found the answer!

py {0:010d}.format(1234)
001234

py {0:010}.format(1234)
001234

py {0:010}.format(1234)
001234

py {0:@10}.format(1234)
@@1234

I would skip using the {int}{repeat}d syntax and just use the string
padding since you won't need to worry about the input data type. I
hate specificity types in string formats. With the old interpolation i
ALWAYS used %s for everything.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Benefit and belief

2011-09-29 Thread rantingrick
On Sep 29, 6:40 pm, Ethan Furman et...@stoneleaf.us wrote:
 Okay, that's what I get for skimming -- it was alex23, not rr.  My
 apologies, rr, for the misattribution.

Oh don't worry Ethan, this is not the first time I've been falsely
accused, misquoted, and kicked in the testicles, and i'm quite sure
with this fine group of folks it won't be the last either.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installing Python 2.6.7 on Windows

2011-09-28 Thread rantingrick
On Sep 27, 11:25 pm, Steven D'Aprano steve
+comp.lang.pyt...@pearwood.info wrote:

 The Python development team is relatively small and chronically busy: too
 much to do and not enough time to do it.

If that is the case then why do they snub their noses at anyone who
wishes to help? What kind of people would chase off good help just to
save ego? I imagine the folks at py dev sort of like a dying man in
need of a heart transplant; the man informs the doctor that he would
happy to get a transplant but not if the heart came from a jew, asian,
african, latin, russian, or canuck.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggested coding style

2011-09-28 Thread rantingrick
On Sep 28, 6:26 pm, Tim Johnson t...@akwebsoft.com wrote:
 * DevPlayer devpla...@gmail.com [110928 04:31]:
  On Sep 27, 10:25 pm, alex23 wuwe...@gmail.com wrote:
   rantingrick rantingr...@gmail.com wrote:
Since, like the bible
the zen is self contradicting, any argument utilizing the zen can be
defeated utilizing the zen.

   And like the Bible, the Zen was created by humans as a joke. If you're
   taking it too seriously, that's your problem.

If however you want to learn about the accepted rules for formatting
code then you need to read PEP-8! PEP 8 is our style guide.

  Contradiction is only seen by narrow perspectve.

  Calling the Bible a joke is used to hurt people, not enlighten them.
  Those words show bitter arrogance, not constructive critism as it
  ignores how others feel about that book. What benefit to others is
  gained by calling someones belief a joke?

  My wife and I are devout christians, but not fundamentalist. We
  would not take rantingrick too seriously. If _you_ take him
  seriously, you're just giving him 'street cred'.

DevPlayer was not even talking about what i said, he was replying to a
statement by Alex23 who said (and i quote) And like the Bible, the
Zen was created by humans as a joke. Maybe you should spend the next
fifteen or so minutes catching up to the conversation...(ಠ_ಠ)...of
course only *after* you clean that egg from your face.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggested coding style

2011-09-27 Thread rantingrick
On Sep 27, 1:51 am, DevPlayer devpla...@gmail.com wrote:
 By the way OP Passiday the title of the topic is Suggested coding
 style.

 Are you suggesting a coding style or asking for a Python coding style
 or are you asking what IS the Python coding style.

 If you are asking what is the Python coding style. Google The Zen of
 Python. It's pretty much the dictum of coding style and referred to
 alot by many Pythoneers.

The Python zen is a very general outline of our collective religious
beliefs concerning programming (and it could be applied to many
fields). Every Python programmer should know the zen by heart. Which
can be very beneficial in a war of words when some smart mouth decides
to quote the zen in an attempt to defeat you. Since, like the bible
the zen is self contradicting, any argument utilizing the zen can be
defeated utilizing the zen.

If however you want to learn about the accepted rules for formatting
code then you need to read PEP-8! PEP 8 is our style guide. It is
not perfect as i have pointed out on many occasions HOWEVER it is the
only thing we have that keeps multiplicity from reproducing like
leporidae.

  http://www.python.org/dev/peps/pep-0008/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is the shutil module called shutil?

2011-09-25 Thread rantingrick
On Sep 24, 11:56 pm, Matt Joiner anacro...@gmail.com wrote:
 Please continue

Well specifically we should have a look over the Ruby API's of File,
Dir, and IO. I don't believe we should copy them verbatim --as the
Ruby API is not Pythonic-- however, it may be a good starting point
for something that has been decades overdue within this community.

There was the rejected Path object from PEP 355:
http://www.python.org/dev/peps/pep-0355/

But it seems the Anointed One tossed the idea due to it's
versatility and it being a subclass of string... is he joking? o_O

First of all, what the hell is wrong with versatility Mr Van Rossum?
Where else would you put these methods? True it may be a large
collection, however, can YOU offer any suggestions as to where else we
would put them or are YOU just going to latch on to your prejudices of
path objects like your irrational fears of functional programming? Do
you remember the map and lambda fiasco?

We need you to get on board and push something through. When you hide
your head in the sand and imagine everything is peachy cream you
expose your backside for a swift kicking.

[References:]

Ruby File Object:
 http://www.ruby-doc.org/core/classes/File.html

Ruby Dir Object:
http://ruby-doc.org/core/classes/Dir.html

Ruby IO Object:
http://www.ruby-doc.org/core/classes/IO.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is the shutil module called shutil?

2011-09-25 Thread rantingrick
Here is a *very* rough outline of my ideas. There are probably a few
mistakes in there. I've decided on three main main objects. A File
object, a Path object, and a Dir object.


## START ENLIGHTENMENT ##

class Path:
def __init__(self, path):
#
# Properties about the path:
drive = str
directory = str
filename = str
extension = str
uncshare[1]= ???
#
# Mutations.
def coerce(self) = File or Dir
def normalize(self): = ip or Path? #normcase/normpath
def expand_user(self): = ip or Path?
def expand_vars(self): = ip or Path?
def absolute(self) = ip or Path? #realpath/abspath
def strip(self) = ip = remove one extension.
def chmod(self, mode) = None
def chown(self, uid, gid) = None [1]
def rename(self, newname) = None
def access(self, mode): = None #access
def chroot(self) = None
#
# Introspection.
def is_valid(self): # exists
def is_absolute(self): #isabs
def is_directory(self): #isdir
def is_file(self): #isfile
def is_link(self): #islnk
def is_mount(self): #ismount
def is_identical(self, other): #issamefile
def time_accessed(self): #atime
def time_modified(self): #mtime
def time_changed(self): #ctime
##def utime(self, times) = None
#
# Inspection.
def info_stat(self): #stat
def info_lstat(self): #lstat
def info_statvfs(self): #statvfs
#
# Extraction.
def basename(self): = str
#Do we need basename when properties exist?
def partition(self) = (drive, path, filename, extension)
#Do we need partition when properties exist?
def splitunc(self): ???
def splitall(self): ???
def relpathto(self, dest): = ???
def pathconf(self, name): #pathconfig
#
# Modifying operations on links
def link(self, newpath): ...
def symlink(self, newlink): ...
def readlink(self): ...
def readlinkabs(self): ...

class File:
def new(path)
(...All existing file methods here...)
#
# Mutate, Clone, Destroy.
def rename(self, newname) = ip or File?
def delete(self, overwrites=3) = None
def copy(self, dst) = File
def unlink(self) = None#
#
# Attribute mutation.
def update(self) = None #touch
def copy_mode(src) = None #copymode
def copy_stat(src) = None #copystat
def update_mode(dst) = None
def update_stat(dst) = None
#
# Other
def bytes(self): = int = 1292894
def size(self, fmtstr={0:0.2f}) = str = 1.23 MB
def backup(self) = filename.bak{count}


class Dir:
def new(path)
def open(path)
#
# Mutate, Clone, Destroy.
def delete(self, onerror=None): = None
def copy(self, dst, symlinks=True): = Dir
#
# Introspection.
def get_paths(self, pattern=None): [Path, Path, ...]
def get_dirs(self, pattern=None): = [Dir, Dir, ...]
def get_files(self, pattern=None): = [File, File, ...]
#
def walk_paths(self, pattern=None): itereach-PathObj
def walk_dirs(self, pattern=None): itereach-DirObj
def walk_files(self, pattern=None): itereach-FileObj
#
def match(self, pattern) = bool
def glob(self, pattern): = [Path, Path, ...]

###
# Not sure what to do with these yet.
###
def startfile(self)
# startfile should part of os anyway.

## END ENLIGHTENMENT ##

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


Re: Why is the shutil module called shutil?

2011-09-25 Thread rantingrick
Oh the creative juices are flowing now!!!



class Path:
def __init__(self, path):
def __coerce__(self) = File or Dir
#
# Properties about the path:
drive = str
directory = str
filename = str
extension = str
##uncshare[1]= ???
#
# Mutations.
def expand_user(self): = ip or Path?
def expand_vars(self): = ip or Path?
def to_normpath(self): = ip #normcase/normpath
def to_abspath(self) = ip #realpath/abspath
def set_access(self, mode) = None
def set_owner(self, uid, gid) = None
def set_root(self, path) = None
#
# Introspection.
def is_accessable(self, mode) = bool #access
def is_valid(self) = bool # exists
def is_absolute(self) = bool #isabs
def is_directory(self) = bool #isdir
def is_file(self) = bool #isfile
def is_link(self) = bool #islnk
def is_mount(self) = bool #ismount
def is_same(self, path_Dir_or_File) = bool #issamefile
#
# Inspection, Extraction
def get_abspath(self)= Path
def get_normpath(self) = Path
##def get_atime(self) = str #atime
##def get_mtime(self) = str #mtime
##def get_ctime(self) = str #ctime
def get_stat(self) = stat #stat,lstat
##def get_statvfs(self) = stat #statvfs
### do we really need this antiquity?


# Question #

# Should all the stat stuff like get_mtime, get_ctime, #
# get_atime, etc... be accessed only under get_stat? I #
# believe so!  #


def get_drive(self): = str
def get_directory(self): = str
def get_filename(self): = str (empty if is_dir)
def get_extension(self): = str (empty if is_dir)
#
def split(self) = (drive, path, filename, extension)
##def splitunc(self): ???
##def splitall(self): ???
##def relpathto(self, dest): = ???
##def pathconf(self, name): #pathconfig
#
# Modifying operations on links
def link_new(self, newpath, symbolic=False): ...
def link_read(self): ...
def link_readabs(self): ...


class File:
def new(path)
(...All existing file methods here...)
#
# Mutate, Clone, Destroy.
def rename(self, newname) = ip or File?
def delete(self, overwrites=3) = None
def copy(self, dst) = File
def unlink(self) = None#
#
# Attribute mutation.
def update(self) = None #touch
def copy_mode(src) = None #copymode
def copy_stat(src) = None #copystat
def update_mode(dst) = None
def update_stat(dst) = None
#
# Other
def get_bytes(self): = int = 1292894
def get_size(self, fmtstr={0:0.2f}) = str = 1.23 MB
def backup(self) = filename.bak{count}


class Dir:
def new(path)
def open(path)
#
# Mutate, Clone, Destroy.
def delete(self, onerror=None): = None
def copy(self, dst, symlinks=True): = Dir
#
# Introspection.
def get_paths(self, pattern=None): [Path, Path, ...]
def get_dirs(self, pattern=None): = [Dir, Dir, ...]
def get_files(self, pattern=None): = [File, File, ...]
def walk_paths(self, pattern=None): itereach-PathObj
def walk_dirs(self, pattern=None): itereach-DirObj
def walk_files(self, pattern=None): itereach-FileObj


# Question #

# Do we really need get_* AND walk_*? I believe we #
# should choose one set of three   #


def match(self, pattern) = bool
# Do we need match when re would suffice?
def glob(self, pattern): = [Path, Path, ...]


# Excommunicated Methods.

def startfile(self)
# startfile should part of os anyway.

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


Re: Python Mixins

2011-09-24 Thread rantingrick
On Sep 22, 4:14 pm, Matt mattj.morri...@gmail.com wrote:
 I'm curious about what people's opinions are about using mixins in
 Python. I really like, for example, the way that class based views
 were implemented in Django 1.3 using mixins. It makes everything
 extremely customizable and reusable. I think this is a very good
 practice to follow, however, in Python mixins are achieved by using
 (or perhaps misusing) inheritance and often multiple inheritance.

Have a look at this article also. Even though he uses java source code
anyone can follow along:

   http://berniesumption.com/software/inheritance-is-evil-and-must-be-destroyed/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is the shutil module called shutil?

2011-09-24 Thread rantingrick
On Sep 23, 10:36 pm, Fletcher Johnson flt.john...@gmail.com wrote:
 The topic says it all:
 Why is shutil named shutil? What does it stand for? This is just a
 mild curiosity of mine.
 The shutil module for 
 reference:http://docs.python.org/library/shutil.html#module-shutil

Because even after 20 freaking years of evolution Python heads of
state (or states of head) cannot be bi-partisan enough to agree on a
freaking File and/or path object; remind you of any body we know?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Mixins

2011-09-24 Thread rantingrick
On Sep 24, 3:57 am, Steven D'Aprano steve
+comp.lang.pyt...@pearwood.info wrote:

 class StandardTestMixin:
     def test_requires_one_argument(self):
         self.assertRaises(TypeError, self.func)
     def test_has_docstring(self):
         self.assertTrue(self.func.__doc__)

And this is another example of why we need doc-string reforms. Here we
have a well know pythonista (for lack of better word) who needs to
write a test for doc-string inclusion because he refuses to get in the
habit of writing them. People, EVERY method and function MUST have a
doc-string! What is the purpose of having doc-strings if we are too
lazy to use them!


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


Re: Python Mixins

2011-09-22 Thread rantingrick
On Sep 22, 4:14 pm, Matt mattj.morri...@gmail.com wrote:

 (although having only a single parent doesn't
 make much sense either, I believe there are very few actual documented
 cases of that happening).

There is nothing wrong with an object having only one parent. Most
times the reasons are for maintainability. I might have a TextEditor
that exposes all the generic functionality that are ubiquitous to text
editors and then a FancyTextEditor(TextEditor) that exposes
functionality that is unique to a confined set of text editing uses. A
silly example, but proves the point. Do not judge an object by the
number of prodigy.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyWart: Itertools module needs attention

2011-09-13 Thread rantingrick
On Sep 13, 10:45 am, Ian Kelly ian.g.ke...@gmail.com wrote:

 Have you looked at the online itertools documentation at all?

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

Yes the online docs are much better. I really like the source code
showing the inner workings of the methods. However i always get upset
when i see poorly thought out doc-strings. My philosophy is that we
should use the built in help function first and only visit the
documentation if more instruction is needed.


I may need to create another PyWart on the topic of doc-strings and
how the author of these strings needs to forget everything he knows
and imagine he is a complete python neophyte. I remember my initial
frustrations learning about functions (in another life it seems) and
my inability to grasp the concept was due to poor examples. I believe
the author use the Fibonacci sequence as an example (Python docs use
this example also). What an idiot!

What does conditionals, linear assignment, loops, the print function,
in-place addition, logic, blah, blah, have to do with understanding a
function... NOTHING! The most basic and by far the best first example
for functions (in any language) is this...

def add(x, y):
return x + y

Followed by this...

def sub(x,y):
return x - y

Simple and to the point. It simply reeks of ah ha! I dare anyone to
create a better introductory function example. Dear Tutorial Writer:
When writing tutorials please check your ego at the door. Thank you.
-- 
http://mail.python.org/mailman/listinfo/python-list


PyWart: Itertools module needs attention

2011-09-12 Thread rantingrick


#  Quote   #

# The itertools module is great HOWEVER i believe most #
# people are recreating the functionalities due to the #
# insanely cryptic and/or missing examples from each   #
# method   #


py print itertools.chain.__doc__
chain(*iterables) -- chain object
Return a chain object whose .next() method returns elements from the
first iterable until it is exhausted, then elements from the next
iterable, until all of the iterables are exhausted.


#  Quote   #

# Okay not TOO bad however this simple example would   #
# suffice: #


py list(itertools.chain([1,2], [3,[4,5],6]))
[1, 2, 3, [4, 5], 6]


#  Quote   #

# Same for these...#


py ''.join(list(itertools.dropwhile(lambda x:x== , hello
word)))
'hello word'
py ''.join(list(itertools.takewhile(lambda x:x== , hello
word)))
''
py print itertools.compress.__doc__
compress(data, selectors) -- iterator over selected data
Return data elements corresponding to true selector elements.
Forms a shorter iterator from selected data elements using the
selectors to choose the data elements.


#  Quote   #

# WTF! Would you like to define a Python selector. Could #
# it be that we should be using selector function or #
# predicate function instead?#

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


Re: How to structure packages

2011-09-07 Thread rantingrick
On Sep 7, 10:56 am, bclark76 bclar...@gmail.com wrote:
 I'm learning python, and was playing with structuring packages.

 Basically I want to have a package called mypackage that defines a
 number of classes and functions.

 so I create:

 mypackage
     __init__.py
     myfunc.py
     MyClass.py

Don't tell me you create a module called myfunc.py??? Stuff that
function in __init__! Also don't name modules MyClass either. Both the
spelling and grammar is incorrect. ALL modules use lowercase (and only
integrate underscores in the most dire of need!)

geom
   __init__.py
   vector3d.py
   point3d.py
   transformation.py

from geom.transformation import Transformation
from geom.vector3d import Vector3d
from geom.point3d import Point3d

or alternatively:

geom
   __init__.py
   from __vector3d import Vector3d
   from __point3d import Point3d
   from __transformation import Transformation
   __vector3d.py
   __point3d.py
   __transformation.py

from geom import Transformation
from geom import Vector3d
from geom import Point3d

Although this method can be brittle due to the fact that one buggy
module can break all the imported code in the __init__ module. I
usually opt for specifying the module in the import path.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter label height to fit content

2011-09-06 Thread rantingrick
Hmm, i can replace all that code with this...

#
# Easy_as.py
#
import Tkinter as tk
from ScrolledText import ScrolledText
import tkFont
import random
# Create some puesdo data.
data = [
'{0}.{1}'.format(x, 'blah'*random.randint(4, 50))
for x in range(100)
]
##print data
# Create the main window and a scrolled text widget.
root = tk.Tk()
font = tkFont.Font(family='times', size=13)
textbox = ScrolledText(
root,
width=60,
height=20,
font=('Times', 10),
wrap=tk.WORD,
)
textbox.pack(
fill=tk.BOTH,
expand=True,
padx=5,
pady=5,
)
textbox.insert(1.0, '\n\n'.join(data))
# Start the event loop.
root.mainloop()
#
# End
#
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter label height to fit content

2011-09-06 Thread rantingrick
Or if you prefer the alternating background approach...


##
# Easy_as.py
##
import Tkinter as tk
from ScrolledText import ScrolledText
import tkFont
import random
END = 'end'
INSERT = 'insert'
#
# Create some puesdo data.
data = [
'{0}.{1}'.format(x, 'blah'*random.randint(4, 50))
for x in range(100)
]
##print data
#
# Create the main window and a scrolled text widget.
root = tk.Tk()
font = tkFont.Font(family='times', size=13)
textbox = ScrolledText(
root,
width=60,
height=20,
font=('Times', 10),
wrap=tk.WORD,
)
textbox.pack(
fill=tk.BOTH,
expand=True,
padx=5,
pady=5,
)
#
# Add a tag to the very end of the widget and
# configure the tag only once!
textbox.tag_add('one', END)
textbox.tag_config('one', background='gray')
#
# Iterate over the lines stuffing them into the textbox.
idata = iter(data)
sidx = 1.0
while True:
try:
textbox.insert(END, idata.next()+\n)
textbox.tag_add('one', sidx, INSERT)
textbox.insert(END, idata.next()+\n)
print sidx, textbox.index(END)
sidx = textbox.index(INSERT)
except StopIteration:
break
#
# Start the event loop.
root.mainloop()
##
# End
##

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


Re: Advice on how to get started with 2D-plotting ?

2011-09-06 Thread rantingrick
On Sep 6, 1:27 pm, Fred Pacquier xne...@fredp.lautre.net wrote:
 I'm a Python long-timer, but I've never had to use tools like Matplotlib 
 others before.

 Now, for my work, I would need to learn the basics fast, for a one-time
 quick-n-dirty job.

##
## START SCRIPT ##
##
#
# Easy_as.py
#
import Tkinter as tk
# Create a main window and a canvas.
app = tk.Tk()
can = tk.Canvas(
app,
width=500,
height=500,
#bd=1,
#relief=tk.SOLID,
)
can.pack(
fill=tk.BOTH,
expand=True,
padx=5,
pady=5,
)
# Create some gridlines on the canvas.
W,H = 500, 500
row, col = 0,0
for _ in range(10):
can.create_line(0, row, W, row, fill='red')
print 0, row, W, row
can.create_line(col, 0, col, H, fill='green')
row += 50
col += 50
can.create_line(
0,500,300,300,
350,200,400,450,
fill='magenta',
width=5,
)
# Start the event loop.
app.mainloop()

## END SCRIPT ##


Any questions?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter label height to fit content

2011-09-06 Thread rantingrick
On Sep 6, 5:00 pm, Bart Kastermans bkast...@gmail.com wrote:
 rantingrick rantingr...@gmail.com writes:
  Hmm, i can replace all that code with this...

 Because I stupidly forgot to repeat the original problem I had, and my
 code doesn't show it (and doesn't show the correct use of the function I
 wrote).

Oh NOW i see! This new code you posted is like night and day compared
to the original /sarcasm :o)

Anyway, i did not read the code to find the difference because i want
to know why you insist on using multiple labels for this when a
scrolled text will suffice. Are you trying to create some sort of
textual animation frames that you can flip through on demand? If not
i would use the scrolled text (and even the scrolled text can feel
like animation frames whist scrolling).

Take your input data and replace ALL single newlines with null strings
(thereby preserving paragraphs) and let the textbox control the line
wrapping. The benefits are enormous using my way; your way is limited
and requires re-inventing the wheel. Tell me WHY the textbox approach
is not a viable solution and THEN i'll listen to you.

Until then; you can lead a horse to water...

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


Re: Tkinter label height to fit content

2011-09-06 Thread rantingrick
On Sep 6, 5:40 pm, rantingrick rantingr...@gmail.com wrote:
 On Sep 6, 5:00 pm, Bart Kastermans bkast...@gmail.com wrote:

 Take your input data and replace ALL single newlines with null strings

CORRECTION: Take your input data and replace ALL single newlines with
A SINGLE SPACE
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to print a module?

2011-09-05 Thread rantingrick
On Sep 5, 10:06 am, Martin De Kauwe mdeka...@gmail.com wrote:
 Hi,

 If I wanted to print an entire module, skipping the attributes
 starting with __ is there an *optimal* way? Currently I am doing
 something like this. Note I am just using sys here to make the point

 import sys

 data = []
 for attr in sys.__dict__.keys():
     if not attr.startswith('__') and not attr.endswith('__'):
         attr_val = getattr(sys, attr)
         data.append((attr, attr_val))
 data.sort()
 for i in data:
     print %s = %s % (i[0], i[1])

 Clearly this would be quicker if I didn't store it and sort the
 output, i.e.

 for attr in sys.__dict__.keys():
     if not attr.startswith('__') and not attr.endswith('__'):
         attr_val = getattr(sys, attr)
         print %s = %s % (attr, attr_val)

 Anyway if there is a better way it would be useful to hear it...

 Many thanks,

 Martin

Martin, have you considered that your custom function is just re-
inventing the built-in dir() function? I would suggest using a list
comprehension against the dir() function with a predicate to remove
anything that startswith '_'. Here's some Ruby code to solve the
problem. I'll let you figure out the Python equivalent.

rb ['_hello', '__goodbye__', 'whatsup'].select{|x| x[0].chr != '_'}
[whatsup]

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


Re: Why do class methods always need 'self' as the first parameter?

2011-09-05 Thread rantingrick
On Aug 31, 9:35 am, T. Goodchild tgoodch...@gmail.com wrote:
 I’m new to Python, and I love it.  The philosophy of the language (and
 of the community as a whole) is beautiful to me.

Welcome aboard mate!

 But one of the things that bugs me

Oh here we go! :-)

  is the requirement that all class
 methods have 'self' as their first parameter.  On a gut level, to me
 this seems to be at odds with Python’s dedication to simplicity.

It will will seem odd at first. I too hated typing all those selfs
all the time. But believe me my new friend in no time those selfs will
roll of your fingers with great ease. You'll forget how much you hate
them and find much more to complain about.

Like for instance: I really lament the missing redundancy of Explicit
Lexical Scoping in python. For me global variables should have to be
qualified.

 For example, consider Python’s indent-sensitive syntax.  
 [...]
 and the result was a significantly improved
 signal-to-noise ratio in the readability of Python code.

Yes, forced indention is my favorite aspect of Python!

 So why is 'self' necessary on class methods?

It could be that Guido has a exaggerated self importance and just
liked the sound of all those selfs whist reading source code. However
i believe the real reason is really readability! It takes a while to
understand this aspect because the natural human response is to be
lazy (for instance i could have used used to in the previous
sentence if i was slothful). We are all inherently lazy beings who
need structure to keep us from spiraling out of control into the abyss
of selfishness.

GvR: Computer Scientist and Behavioral psychologist.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow line break at operators

2011-09-04 Thread rantingrick
On Sep 3, 11:50 am, Stephen Hansen me+list/pyt...@ixokai.io wrote:

 Freedom is not and never has been, IMHO, a virtue or goal or even desire
 in Python.

Exactly!

 Where it occurs, it is at best a happy coincidence,

Exactly!

 and even
 if that happy coincidence happens often, it is not a design feature, IMHO.

Exactly! Actually i believe Python allows TOO many freedoms and
indulges TOO many excesses to the detriment of our code bases. Take
the fact that both tabs AND spaces are legal in Python source. We
should have choose one over the other!

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


Re: allow line break at operators

2011-09-04 Thread rantingrick
On Sep 4, 10:22 am, ron3200 ron3...@gmail.com wrote:

 I think this is one of those areas where computers and people differ,
 but it may also depend on the persons native language as to what works
 better for them.

Yes but what works better for them is not always a better way of
doing things! People do foolish things all the time just from pure
habit. A foolish consistency is a foolish consistency my friend. I
mean, look at the folks who popped their cherry writing Basic code;
talk about dysfunctional!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter label height to fit content

2011-09-04 Thread rantingrick
On Sep 4, 2:39 pm, Bart Kastermans bkast...@gmail.com wrote:

 I get bits of information over RSS, these are of varying length.  I
 want to show 10 at a time, and scroll through them.  Now when I
 scroll the window grows and shrinks depending on their size, I want
 to right from the start make it high enough to contain even the
 biggest that will have to be shown.  So the question is determining
 the height parameter for the labels ahead of time.  My strategy has
 been to put all in labels and then try to get the information from
 the label of how high it needs to be made at a certain width.

I see. However i might opt instead for a text widget with columns of
wrapped text. You could use the textwrap.py module to help (although
you'll have to work around it's shortcomings for paragraphs and such).
In any event it's difficult to offer good advice without seeing the
code directly.


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


Re: Tkinter label height to fit content

2011-09-04 Thread rantingrick
On Sep 4, 2:39 pm, Bart Kastermans bkast...@gmail.com wrote:

 Thx.  That function should allow for a bit of robustness.

Correction. The function is actually tkFont.metrics(arg) which takes
linespace as an optional argument.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter label height to fit content

2011-09-03 Thread rantingrick
On Sep 3, 5:15 pm, Bart Kastermans bkast...@gmail.com wrote:

 Any suggestions?

Yeah, have you considered using the linespace() method of tk.Font
objects to calculate the height? Although i must say it feels as if
your doing something you should not need to do, however i cannot be
sure without knowing more about this GUI. Sounds a lot like trying to
put socks on a rooster.

http://infohost.nmt.edu/tcc/help/pubs/tkinter/std-attrs.html#fonts
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there any principle when writing python function

2011-08-27 Thread rantingrick
On Aug 27, 5:21 pm, Emile van Sebille em...@fenx.com wrote:
 On 8/27/2011 2:57 PM Ben Finney said...

  Emile van Sebilleem...@fenx.com  writes:

  Code is first and foremost written to be executed.

       “Programs must be written for people to read, and only incidentally for
       machines to execute.”
       —Abelson  Sussman, _Structure and Interpretation of Computer Programs_

 That's certainly self-fulfilling -- code that doesn't execute will need
 to be read to be understood, and to be fixed so that it does run.
 Nobody cares about code not intended to be executed.  Pretty it up as
 much as you have free time to do so to enlighten your intended audience.

 Code that runs from the offset may not ever again need to be read, so
 the only audience will ever be the processor.

WRONG!

Code may need to be extended someday no matter HOW well it executes
today. Also, code need to be readable so the readers can learn from
it.

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


Re: is there any principle when writing python function

2011-08-26 Thread rantingrick
On Aug 26, 6:15 am, Roy Smith r...@panix.com wrote:

 Maybe.  In general, it's certainly true that a bunch of smallish
 functions, each of which performs exactly one job, is easier to work
 with than a huge ball of spaghetti code.  

Obviously you need to google the definition of spaghetti code. When
you move code out of one function and create another function you are
contributing to the spaghetti-ness of the code. Think of plate of
spaghetti and how the noodles are all intertwined and without order.
Likewise when you go to one function and have to follow the trial of
one or more helper functions you are creating a twisting and unordered
progression of code -- sniff-sniff, do you smell what i smell?

Furthermore: If you are moving code out of one function to ONLY be
called by that ONE function then you are a bad programmer and should
have your editor taken away for six months. You should ONLY create
more func/methods if those func/methods will be called from two or
more places in the code. The very essence of func/meths is the fact
that they are reusable.

It might still be spaghetti under that definition (of which ALL OOP
code actually is!) however it will be as elegant as spaghetti can be.

 On the other hand, interfaces
 are a common cause of bugs.  When you pull a hunk of code out into its
 own function, you create a new interface.  Sometimes that adds
 complexity (and bugs) of its own.

Which is it? You cannot have it both ways. You're straddling the fence
here like a dirty politician. Yes, this subject IS black and white!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there any principle when writing python function

2011-08-26 Thread rantingrick
On Aug 26, 10:40 am, John Gordon gor...@panix.com wrote:
 In 7b47ca17-d3f1-4d91-91d1-98421e870...@ea4g2000vbb.googlegroups.com 
 rantingrick rantingr...@gmail.com writes:

  Furthermore: If you are moving code out of one function to ONLY be
  called by that ONE function then you are a bad programmer and should
  have your editor taken away for six months. You should ONLY create
  more func/methods if those func/methods will be called from two or
  more places in the code. The very essence of func/meths is the fact
  that they are reusable.

 That's one very important aspect of functions, yes.  But there's another:
 abstraction.
 [...]
 The main module keeps a high level of abstraction instead of descending
 into dozens or even hundreds of lines of LDAP-specific code.

Exactly. I am not arguing against creating intuitive and
simplistically elegant interfaces. I mean, lists *could* have only one
method called apply(process, *args, **kw) which takes an argument like
(append, value) or (index, 42) and has a long block of logic to
handle the inputs however that would be a horrible interface.

So in that respect i agree. We must weigh the entire interface from an
empirical perspective. However i can be sure of one point: As you
increase the number of methods you also increase the mental load
required to understand that particular interface.

An interface with a small number of methods will not suffer too
terribly from one or two extra methods however at some point more
methods just equals more confusion. It is a delicate balancing act
that many programmers are not agile enough to juggle elegantly.

Take for instance the interface for Grep, Search, and Replace dialogs
in the idlelib which span two separate modules and have a mind numbing
number of methods for such remedial things as creating buttons and
entrys. All three dialogs look very similar and share many
similarities.

Now take a look at MY simple ONE module solution. It has JUST enough
methods and NOT a single more! Yes the create widgets method is fairly
long (weighing in at 80+ lines with comments!) however all of this
code needs to be contained in ONE and ONLY one method. Heck if i
wanted to get pendantic i could replace the five cb_*() methods with
partials however MY interface is so intuitive there is no need.


# START CODE

class FindReplaceDialog(object):
def __init__(self, textbox):
[...]

def create_widgets(self, type_):
# Create toplevel dialog window.
[...]
# Create widgets belonging to both
# search AND replace dialogs dialogs.
[...]
if type_ == 'replace':
# Add widgets unique to replace
# dialogs.
[...]
elif type_ == 'grep':
# Add widgets unique to grep
# dialogs.
[...]
# Load any initial values and states.
[...]

def show(self, type_='find'):
self.create_widgets(type_)
# Do any initial setup.

def close(self, event=None):
# destroy the dialog.

def find_again(self, event=None):
# Event callback bound to textbox.

def find(self, target):
# Search the buffer for target and
# hilight if found.

def replace(self, action='replace'):
# Fetch the old and new strings and
# mediate the work depending on the
# action.
[...]
if action == 'replace+find':
[...]
elif action == 'replaceall':
[...]

def grep():
[...]

def cb_grepbutton(self, event=None):
self.grep(target.entry.get())

def cb_findbutton(self, event=None):
self.find(target.entry.get())

def cb_replacebutton(self):
self.replace(action='replace')

def cb_replacefindbutton(self):
self.replace(action='replace+find')

def cb_replaceallbutton(self):
self.replace(action='replaceall')

# END CODE


Now look at the three modules in idlelib (Grep Dialog, Search Dialog,
and Replace Dialog) and ask yourself which is cleaner? Which is more
intuiitve? Which is more professional? Which would you rather debug?

*scholl-bell-rings*
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there any principle when writing python function

2011-08-26 Thread rantingrick
On Aug 26, 4:45 pm, Chris Angelico ros...@gmail.com wrote:
 On Sat, Aug 27, 2011 at 4:05 AM, rantingrick rantingr...@gmail.com wrote:
  Now take a look at MY simple ONE module solution. It has JUST enough
  methods and NOT a single more!

 I disagree - create_widgets() is completely unnecessary in the
 presence of show(),

Well since you cannot see the underlying code i won't be too harsh on
you :), but yes, i can assure you that create widgets IS necessary for
readability. show() calls self.create_widgets() then adds a special
hit tag to the text widget and sets up a modal behavior of the dialog,
it's only 5-7 lines of setup code but i think the separation is
warranted.

Could i have rolled all the create_widgets() code into the show()
method? Of course, however i do see a good reason for separation here
for the sake of readability. Although i must admit, had the interface
been much larger i most assuredly would have rolled it together.

 unless it's possible to show the dialog, hide it,
 and then re-show it without recreating the widgets.

Yes the instance lives on between session to save state. Also the
find_again binding of the text widget calls the
SearchReplaceDialog.find_again() method when {CONTROL+G} event fires.

 I'm sure there are. But let's face it: We're programming in PYTHON.
 Not C, not Erlang, not Pike, not PHP. Python. If this has been the
 right choice, then we should assume that efficiency isn't king, but
 readability and maintainability probably are; so the important
 considerations are not will it take two extra nanoseconds to
 execute but can my successor understand what the code's doing and
 will he, if he edits my code, have a reasonable expectation that
 he's not breaking stuff. These are always important.

Bravo! That has to be most lucid and intelligent statement from you to
date. And i must say the warm fuzzies i got from imagining the defeat
D'Aprano must have felt whist reading it left me with a nice feeling.

How do like them apples, D'Aprano? :-)

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


Re: is there any principle when writing python function

2011-08-26 Thread rantingrick
On Aug 26, 1:16 pm, Steven D'Aprano steve
+comp.lang.pyt...@pearwood.info wrote:

 (3) Fault isolation. If you have a 100 line function that fails on line 73,
 that failure may have been introduced way back in line 16. By splitting the
 function up into smaller functions, you can more easily isolate where the
 failure comes from, by checking for violated pre- and post-conditions.

What's wrong Steven, are track backs too complicated for you?


# START DUMMY SCRIPT

def very_long_function():
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(object)
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
max(range(5))
#
print 'blah'
print 'blah'
print 'blah-blah'
very_long_function()

# END DUMMY SCRIPT


Traceback (most recent call last):
  File C:/Python27/test3.py, line 48, in module
very_long_function()
  File C:/Python27/test3.py, line 26, in very_long_function
max(object)
TypeError: 'type' object is not iterable

Oh the humanity!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: there is a problem, holp someone could help me,thanks

2011-08-24 Thread rantingrick
On Aug 24, 10:59 am, kangshu...@hotmail.com wrote:
 Now I have a problem and I holp someone can help me.

 def fib(x):
     if x==0 or x==1: return 1
     else: return fib(x-1) + fib(x-2)

This must be from How not to program. Was this a personal pick or
recommendation?


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


Re: I think I found 2 undocumented string format codes.

2011-08-24 Thread rantingrick
On Aug 24, 3:45 pm, Bill bsag...@gmail.com wrote:
 My google-fu has failed me in finding info on %h and %l string
 formatting codes.

Did it ever occur to you to peruse the docs?
http://docs.python.org/library/stdtypes.html#string-formatting-operations

Stop using the limited deprecated string interpolation and use the new
string format method.
http://docs.python.org/library/string.html#format-string-syntax
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there any principle when writing python function

2011-08-23 Thread rantingrick
On Aug 23, 6:59 am, smith jack thinke...@gmail.com wrote:
 i have heard that function invocation in python is expensive, but make
 lots of functions are a good design habit in many other languages, so
 is there any principle when writing python function?
 for example, how many lines should form a function?

Everyone here who is suggesting that function bodies should be
confined to ANY length is an idiot. The length of a functions code
block is inconsequential. Don't worry if it too small or too big. It's
not the size that matters, it's the motion of the sources ocean!

A good function can be one line, or a hundred lines. Always use
comments to clarify code and NEVER EVER create more functions only for
the sake of short function bodies, WHY, because all you do is move
confusion OUT OF the function body and INTO the module/class body.

Energy can neither be created nor be destroyed: it can only be
transformed from one state to another

http://en.wikipedia.org/wiki/Conservation_of_energy
https://sites.google.com/site/thefutureofpython/

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


Re: is there any principle when writing python function

2011-08-23 Thread rantingrick
On Aug 23, 1:29 pm, Terry Reedy tjre...@udel.edu wrote:

 In terms of different functions performed (see my previous post), I see
    attribute lookup
    assignment
    enumerate
    sequence unpacking
    for-looping
    if-conditioning
    lower
    startswith
    return
 That is 9,  which is enough.


attribute lookup - inspection
assignment - ditto
enumerate - enumeration
sequence unpacking - parallel assignment
for-looping - cycling
if-conditioning - logic
lower - mutation (don't try to argue!)
startswith - boolean-logic
return - exiting (although all exits require an entrance!)
omitted: documenting, referencing, -presumptuousness-

pedantic-ly yours, rr
;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List spam

2011-08-18 Thread rantingrick
On Aug 18, 8:39 am, Jason Staudenmayer
jas...@adventureaquarium.com wrote:

 [snip irony]

 Adventure Aquarium is America's Most Touchable Aquarium!
 Featuring the ALL NEW Stingray Beach Club
 Where you can touch and hand feed the gentle stingrays

 To buy and print your tickets at home visit  www.AdventureAquarium.com
       ..·º..·`·.º..·`·.º..·`·.º
                                     ..·`·.º..·`·.º..·`·.º
 ..·º..·`·.º

 A Herschend Family Entertainment Company

Don't you find it a bit ironic that you are complaining about spam but
yet you are spamming this group with your link to buy tickets to a
stingray petting zoo (which is in fact an oxymoron?) under the guise
of spam bashing?  Tip of the day: Create a website!

PS: I do however find the recent rape spam atrocious!


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


Re: Ten rules to becoming a Python community member.

2011-08-16 Thread rantingrick
On Aug 16, 2:07 am, alex23 wuwe...@gmail.com wrote:

 All the way down indeed. Can you pick who said these?

Obviously your grep skills are superb however you need to brush up on
those reading and comprehension skills a bit.

 There are noobs watching and we to provide code that can be used to
 teach!

Yes i said this, however the use of used to is proper here. -1

 And just what *point* an i supposed to be getting Stephen?

Yes i said this, and it may seem that you have me on this one
however i believe that Stephen had said something like you are
supposed to blah, blah and i retorted with oh, and just what
*point* am i supposed to blah blah blah... although i DID forget
to quote supposed to, still it's a -1.

 An end user should NEVER EVER have to write glue code so their
 abstraction of choice can be used to to script an API.

Yes i said this, however AGAIN the use of used to is proper here.
-1.

sorry alex, better luck next time :(. Follows is some homework i have
prepared for you so that you can understand the proper and improper
usage of used to.

Incorrect past tense usage of used to:
  I used to wear wooden shoes 

Incorrect description using used to:
  I have become used to wearing wooden shoes 

Correct usage of used to:
  Wooden shoes can be used to torture someone 

For our next assignment we'll be learning about the exploits of Jack
and Jill.

 (For bonus points: can you also spot who is bored at work today?)

Trolling doesn't count as work unless you're being paid for it,
however some people might consider you a pro by now!

PS: Does anyone notice how Stephen has fallen off the face the earth?
Where is Stephen i wonder? He was such a vocal nuisance and then he
just disappeared. It seemed like he appeared as strangely as he
disappeared. Well, he's probably where most sock puppets go when they
have no further usage.

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


Re: Why no warnings when re-assigning builtin names?

2011-08-16 Thread rantingrick
On Aug 16, 9:13 am, Philip Semanchuk phi...@semanchuk.com wrote:

 Sometimes X is safe and sometimes it isn't can be said
 of many, many things, from taking a walk down the street
 to juggling with knives. But it has little to do with
 whether or not Python should issue a warning in the
 specific case we're talking about.

I think any Python n00b should be writing code in n editor that is
safe for beginners AND is also teaching tool. IDLE is probably the
best thing a new Python programmer could use. It has syntax hilight,
smart indention, call tips, code completion, a class browser, greping
tools, and more! I do admit the tool is lacking in many areas
(including code base) that would be atrocious to an experienced
Pythonista, however, the tool is perfect for n00bs (and myself and
other pythoinistas use it all the time!)

 There's a lot of ground to cover between newcomer who has
 learned about a particular warning and coder who
 regularly shadows builtins on purpose.

One word: SYNTAX HILIGHT

 I have never shadowed a builtin deliberately. I've done it
 accidentally plenty of times. There are 84 builtins in my
 version of Python and I don't have them all memorized. The
 fact that my editor colors them differently is the only
 thing I have to back up my leaky memory. Not all editors
 are so gracious.

So you have syntax hilight however you still shadow builtins?  Oh
dear, this problem is worse than i initially suspected!

 You can coerce any example to apply to an argument for or
 against such a warning, but I think the general case is
 that Python could reduce unintended consequences by
 warning when vars erase builtins.  (=== How many builtins
 did I use in that sentence?)

Well let's see:

py import keyword
py import __builtin__
py PY_KWS = keyword.kwlist
py PY_BLT = dir(globals()['__builtins__'])
py s = \
You can coerce any example to apply to an argument for or against such
a warning, but I think the general case is that Python could reduce
unintended consequences by warning when vars erase builtins. 
py fmtstr = '{0} - {1}'
py for word in s.split(' '):
... if word in PY_BLT:
... print fmtstr.format('builtin', word)
... elif word in PY_KWS:
... print fmtstr.format('KeyWord', word)
...
builtin - coerce
builtin - any
builtin - apply
KeyWord - for
KeyWord - or
KeyWord - is
builtin - reduce
builtin - vars
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow line break at operators

2011-08-16 Thread rantingrick
On Aug 16, 1:49 am, alex23 wuwe...@gmail.com wrote:
 On Aug 16, 2:37 pm, rantingrick rantingr...@gmail.com wrote:

  The reading proceeds naturally from right to left.

 Well, naturally if you're coding in Hebrew or Japanese perhaps :)

Yes :). I typo-ed that one. It was getting late when i sent that
reply. I did consider posting an edit however i decided not to and
instead, wait and see who would notice.

The map feels much better too as a consequence:

rb [3,100,-20].map{|x| x.to_f}
[3.0, 100.0, -20.0]

And you can can induce some logic without a clunky lambda.

rb[3,100,-20].map{|x| if x  99 then x.to_f else x end}
[3.0, 100.0, -20.0]

in Python you'd have to create a def for that (i know bad specific
example but the need is there)

It feels just like a Python list comprehension though:
py [float(x) for x in [3,100,-20]]

Even though it reads in a non-linear way, you could argue that the
most important part (float(x)). is front-and-center. Of course i like
the compactness of python's map function:

py map(float, [3,100,-20])

But all too often the map function is insufficient AND you cannot use
map in a chain! If only we could find a happy medium between Python
and Ruby oh what a bliss that would be. We could cut off all of
Pythons warts and destroy all of Rubys multiplicity and singular
paridigm-ness.

 * Forced indention (exactly one tab, and one tab only!)
 * No multiplicity!
 * Nice linear expressions!
 * Name spaces!
 * Implicit modules!
 * Only truly heterogeneous built-in functions allowed!
 * Enough freedom to be expressive, but not enough to allow sloppy-
ness.


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


Re: Ten rules to becoming a Python community member.

2011-08-16 Thread rantingrick
On Aug 16, 1:37 pm, Martin P. Hellwig martin.hell...@gmail.com
wrote:

 Well admittedly English isn't my native language, But indeed all
 sentences seem correct to me.

 With the first sentence meaning: in the past I wore wooden shoes, but
 presently I do not.

 With the second sentence meaning: in the past I was not used to (i.e.
 uncomfortable, hey bonus points!) wearing wooden shoes, but presently I
 am used to it (although not necessarily comfortable, but at least not
 uncomfortable).

 I actually can't figure out a way of saying those two sentences more
 concise or correct then it has been given.

If conciseness is all you seek then perhaps you prefer the following?

ORIGINAL: I used to wear wooden shoes
CONCISE:  I wore wooden shoes
  I wore wood shoes
  Iwood shoes

ORIGINAL: I have become used to wearing wooden shoes
CONCISE:  I like wearing wooden shoes
  I like wooden shoes
  I like wood shoes
  wood shoes: +1

However as you can see much of the rich information is missing. Good
communication requires that we use clear and articulate words (and
phrases) that will re-create a similar thought (if not perfect clone
of!) in the mind of your listener[s].

Of course we should never seek to be overly elaborate and ornate in
our speech unless that is the point (As in poetry, philosophy, and
music which are elaborate and ornate for good reason!).

Likewise we should never seek to be overtly simplistic and dull with
our speech. (As in txt speak which is too simplistic and dull for
intelligent conversation but it has a niche appeal among the children
and idiots)

Think of speaking with articulation as an extension of your body image
GO==GI[1]: You put in too much effort and you become a disgustingly
self gratifying gorilla strutting on the stage of bombast-ity
flexing and posing whist your skin glistens from the oils of your own
mental masturbation. Likewise, if you put in too little effort you
become a disgustingly self gratifying couch potato consumed by
lethargy and atherosclerosis completely covered with the crumbs of
your own mental refuse.

It would be wise (my friend) to find a happy medium.

[1] Garbage Out equals Garbage In(ternally)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ten rules to becoming a Python community member.

2011-08-16 Thread rantingrick
On Aug 16, 4:55 pm, David Monaghan monaghand.da...@gmail.com wrote:
 On Tue, 16 Aug 2011 13:13:10 -0700 (PDT), rantingrick

 rantingr...@gmail.com wrote:
 If conciseness is all you seek then perhaps you prefer the following?

 ORIGINAL: I used to wear wooden shoes
 CONCISE:  I wore wooden shoes
 ORIGINAL: I have become used to wearing wooden shoes
 CONCISE:  I like wearing wooden shoes
 However as you can see much of the rich information is missing.

 Indeed. Neither of your two concise examples has the same meaning of the
 originals.

Really? Are you sure?


 ORIGINAL1: I used to wear wooden shoes


CONCISE_1a: I wore wooden shoes
the word wore is past tense and can be replaced with the past
tense phrase of used to wear without changing any meaning
whatsoever -- albeit the latter is childish!

CONCISE_1b: I wore wood shoes
Wooden = object made of wood = flesh of a tree
Wood = the flesh of a tree
Completely interchangeable!

CONCISE_1c: Iwood shoes
Considering that I is an object that has overloaded the left shift
operator with an instance method to append a single argument (in this
case wood shoes) to instance I's feet. Obviously if an object
didn't like wooden shoes it would not have a method that accepts
them...  yeah it's a bit of a stretch, but not so much that it's
impossible to comprehend!


 ORIGINAL_2: I have become used to wearing wooden shoes


CONCISE_2a:  I like wearing wooden shoes
the word like is a positive present tense inflection of emotion as
it regards to wooden shoes; as is the phrase become used to --
albeit the latter is childish.

CONCISE_2b:  I like wooden shoes
If you like wooden shoes it's only natural to assume that you would
wear them.

CONCISE_2c:  I like wood shoes
Wood, Wooden, we've been here before.

CONCISE_2d:  wood shoes: +1
Since the fact about wearing them can go without being said, you get
the picture... although this too is a stretch, but not impossible!



 Different phrasings of all but the most basic sentences often have subtle
 differences of meaning which native speakers intend and understand. 1984 has
 been and gone. Shame on you!

Guido himself admitted that hidden descriptors are real. The inception
has begun!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ten rules to becoming a Python community member.

2011-08-16 Thread rantingrick
On Aug 16, 6:25 pm, John Gordon gor...@panix.com wrote:
 In d577aa97-84f1-48ac-91fd-4355059ca...@f7g2000vba.googlegroups.com 
 rantingrick rantingr...@gmail.com writes:

  
   ORIGINAL1: I used to wear wooden shoes
  
  CONCISE_1a: I wore wooden shoes

 wore does not convey the same meaning as used to wear.

 wore means you have worn them in the past.

 used to wear means you have worn them in the past AND don't intend
 to do so again.

Actually that assertion is wrong.

Take (in the extreme example) that you were (in the past) forced to
wear a tutu. You did not like wearing the tutu but someone put a gun
to your head, so you did it. Now. If later someone asks you Have you
ever been forced to wear anything you did not like? and you replied
Yes, i wore a tutu [once], there is no way anyone could extrapolate
from that statement whether or not you would NEVER wear a tutu again.

So the moral is: Just because something happened in the past does not
mean it will happen in the future. The fact remains that wore and
used to wear both compile down to the same past tense event
HOWEVER neither have the capacity to predict future events.

No one can predict the future. Not even YOU can predict whether or not
you will wear a tutu again. You may say you would never wear a tutu
again however you can NEVER be sure about that statement without a
time machine, and lots of free time.

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


Re: Ten rules to becoming a Python community member.

2011-08-16 Thread rantingrick
On Aug 16, 7:33 pm, John Gordon gor...@panix.com wrote:
 In ef0722a3-59ff-4fc3-87a9-e637ce9e2...@en1g2000vbb.googlegroups.com 
 rantingrick rantingr...@gmail.com writes:

   wore means you have worn them in the past.

   used to wear means you have worn them in the past AND don't intend
   to do so again.
  Actually that assertion is wrong.
  No one can predict the future. Not even YOU can predict whether or not

 Of course -- that's why the word intend was part of my answer.  Did you
 overlook that crucial word?

 I stand by my assertion that the phrase I used to do X carries the
 meaning that you have done X in the past but DO NOT INTEND to do so
 in the future.

Okay and i'm with you as long as you'll also agree that i wore wooden
shoes carries the meaning that i've worn shoes in the past but gives
no indication that i will wear shoes again. And if you agree with that
(which is a fact BTW) then you must also agree that i used to wear
wear wooden shoes also gives no guarantee that i won't wear them
again.

This point i have been trying to make all along is: Speaking with this
verbiage leaves to much to be desired. To much meaning is specific
*only* to the sender and prone to cause subtle errors upon receiving
due to errors of the lost-in-translation kind. We must remove these
ambiguities from our speech and from our code if we ever expect to
evolve into a species capable of taking the next logical step in our
evolution. That step will require massive amounts of coherent and
articulate collaboration across many cultures. How do solve that
problem you ask? By removing all cultures and joining the culture of
Mankind.

We know that knowledge is being spread far and wide and to every
corner of this planet. No one will ever be robbed of an education
because all the knowledge is being cataloged in the world wide library
(WWW). A person living in a mud hut in Africa has the same access to
the knowledge base as a professor working at a prestigious college. No
more will the class structure be relevant because knowledge IS power.

The playing fields are beginning to be leveled and the world is on
course for a huge shake up soon. How soon this event will culminate
into reality is yet to be known however i can assure you people that
at our current rate, sadly it is going to be a very long time!

The transition is not evolving as fast as it should be because we
refuse to eradicate the enormous amounts of multiplicity that plague
our knowledge bases. Language is one of the top offenders, which
manifest itself over and over like a stupidity virus; and the worst
part is that it shows no readily perceivable symptoms to the zombie
masses! These masses of hosts continue on day after day infecting
new people with this disease of multi-language-ism and as such entropy
grows. Leaps are made but then setbacks are certain due to entropy. On
and on we continue to be slung back and forth due to this elastic
rubber band of stupidity.

Some folks get emotional when i speak of these things. They confuse
multiplicity with freedom. They fear the loss of their freedom to be
lazy, slothful, and stupid. Yes you have a right to be these things if
you want, but don't be expecting that your gene-pool will be part of
the future because you will be bred out of existence!

The future belongs to the intelligent agents capable of eradicating
multiplicity and harnessing what mother nature could never harness
with billions and billions of years built on innumerable random
guesses... the future belongs to those with an IMAGINATION!

An imagination is the most power tool we posses. With imagination we
can drive evolution. Without imagination nothing you see or know would
exist. We would be caught forever in the infinite loop of ape-ian
stupidity and left to wither as just a blip on the evolutionary
radar.

With our imagination we can not only harness our world but also our
universe (which is far more expansive than we have yet to realize). We
can even harness evolution itself! We can transcend the flesh, and
then, THEN... we shall take our rightful place as the gods! Maybe
there is even an evolution of the gods of which replacements are
created every trillion or so years. We are next in line to replace the
aging gods that now control the known universe.

To continue to deny that we are natures greatest creation would be
tantamount to bitch slapping our very own mothers. Instead we should
make her proud by being all that we can be and using our intelligence
to utterly destroy her and IN EFFECT become something greater in the
process than we ever where before. Progress progresses by the
prodigy standing on the shoulders of the creators to reach that next
higher cookie jar.

The future is not saving the whales or the dolphins, or the endangered
three toed alligator. Neither is the future save the earth. The
future is transcendence from the flesh into a new state of being. No
form of matter how well we maintain this earth, one day the sun will
consume

Re: allow line break at operators

2011-08-15 Thread rantingrick
On Aug 15, 2:31 am, Terry Reedy tjre...@udel.edu wrote:
 On 8/15/2011 12:28 AM, Seebs wrote:

 To repeat again: you are free to put in explicit dedent markers that
 will let you re-indent code should all indents be removed.


As Terry has been trying to say for a while now, use the following
methods to quell your eye pain.


 Use pass statement:


if foo:
if bar:
baz
else:
pass
else:
quux


 Use comments:


if foo:
if bar:
baz
#else bar (or endif or whatever you like)
else:
quux


 Use road signs: :-)


# [Warning: Curves Ahead: Eyeball Parse limit 35 WPM!]
if foo: # [Exit 266: foo] --
# [Right Curve Ahead: slow eyeball parsing to 15 WPM!]
if bar:
baz
else:
pass # -- [Warning: Do not litter!]
else: # [Exit 267: Not Foo] --
# [Right Curve Ahead: slow eyeball parsing to 15 WPM!]
quux
...
# [Eyeball Parse limit 55 WPM!]
...
# [PSA: Friends don't let friends write asinine code]
...
# [Next Rest Stop: NEVER!]



Now you have the nice triangular shape that your eyes have been
trained to recognize! I would suggest to use comments whenever
possible. Of course there will be times when you cannot use a comment
and must use an else clause.

Now you have nothing to complain about :).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why no warnings when re-assigning builtin names?

2011-08-15 Thread rantingrick
On Aug 15, 5:13 pm, Philip Semanchuk phi...@semanchuk.com wrote:
 On Aug 15, 2011, at 5:52 PM, Gerrat Rickert wrote:

  With surprising regularity, I see program postings (eg. on
  StackOverflow) from inexperienced Python users  accidentally
  re-assigning built-in names.

  For example, they'll innocently call some variable, list, and assign a
  list of items to it.

  ...and if they're _unlucky_ enough, their program may actually work
  (encouraging them to re-use this name in other programs).

 Or they'll assign a class instance to 'object', only to cause weird errors 
 later when they use it as a base class.

 I agree that this is a problem. The folks on my project who are new-ish to 
 Python overwrite builtins fairly often.

Simple syntax hilighting can head off these issues with great ease.
Heck, python even has a keyword module, and you get a list of built-
ins from the dir() function!

import keyword
import __builtin__
PY_BUILTINS = [str(name) for name in dir(__builtin__) if not
name.startswith('_')]
PY_KEYWORDS = keyword.kwlist

Also Python ships with IDLE (which is a simplistic IDE) and although i
find it needs a bit of work to be what GvR initially dreamed, it works
good enough to get you by. I always say, you must use the correct tool
for the job, and syntax hilight is a must have to avoid these
accidents.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow line break at operators

2011-08-15 Thread rantingrick
On Aug 15, 11:13 pm, alex23 wuwe...@gmail.com wrote:
 Steven D'Aprano steve+comp.lang.pyt...@pearwood.info wrote:
  I think I would be less skeptical about fluent interfaces if they were
  written more like Unix shell script pipelines instead of using attribute
  access notation:

  foo.array_of_things | sort | map block | join , 

 I've seen at least one attempt to provide this in Python:

If you want 100% OOP then use Ruby:

rb [3,100,-20].sort.join('#')
-20#3#100

Ruby is great from this angle! The reading proceeds naturally from
right to left. I have become accustomed to reading Python's nested
function calls however it does feel much more natural in Ruby. Of
course, there are architectural reasons why Python cannot do this
linear syntactical processing which lends some paradigm-al niceties to
the python programmer that are not available to the Ruby folks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ten rules to becoming a Python community member.

2011-08-15 Thread rantingrick
On Aug 15, 7:48 pm, Gregory Ewing greg.ew...@canterbury.ac.nz wrote:
 rantingrick wrote:
  Used to and supposed to is the verbiage of children
  and idiots.

 So when we reach a certain age we're meant to abandon
 short, concise and idomatic ways of speaking, and substitute
 long words and phrases to make ourselves sound adult and
 educated?

Well that is the idea anyway. Not that we should be overly pedantic
about it of course, however some words need to be cast off before we
leave the primary school playground in the name of articulate
communication.

These specific phrases i have pointed out (used to and supposed
to) are a result of a mind choosing the easy way out instead of
putting in the wee bit more effort required to express one's self in
an articulate manner. Also these two phrases are quite prolifically
used within his community (among others), from the BDFL on down. It's
a slippery slope my friend.
-- 
http://mail.python.org/mailman/listinfo/python-list


Ten rules to becoming a Python community member.

2011-08-14 Thread rantingrick

Follow these simply rules to become an accepted member of the Python
community.


1. Bash rantingrick and Xah Lee every chance you get.

2. Bash people who bash rick or xah because their basing made rick's
or xah's words pass through your spam filter.

3. Post links to xkcd as often as you can. Don't worry if they have
been posted a thousand times, just post them because it equals geek
cool points.

4. When the chance presents itself, make snide comments about lisp and
perl; but NEVER about Ruby! (even though Ruby is Perl's micro
minion!).

5. Use fancy words like tail recursion, just because you read about
it on Guido's blog once (even if you have no idea what that means)!

6. Engage in heated and pointless discussions as to whether Python is
pass-by-reference or pass-by-value even if you have no idea what
the hell you are talking about.

7. Play devils advocate often e.g., If someone hates Tkinter: then
argue how great Tkinter is regardless of how much you actually care,
use, or know about the module. Likewise if someone likes Tkinter: then
argue how terrible Tkinter is and how Python does not need any GUI
library; again, regardless of how much you actually care, use, or know
about the module.

8. Use e.g. as many times as you can! (e.g. e.g.) If you use e.g.
more than ten times in a single post, you will get an invite to
Guido's next birthday party; where you'll be forced to do shots whist
walking the balcony railing wearing wooden shoes!

9. Never use the word previously or the phrase in the past; just
dumb it down with used to.

10. Finally, if you get caught using the word that incredibly
excessively, just hope that nobody notices that that that you are
really GvR in disguise.

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


Re: Ten rules to becoming a Python community member.

2011-08-14 Thread rantingrick
On Aug 14, 12:57 am, rantingrick rantingr...@gmail.com wrote:

 9. Never use the word previously or the phrase in the past; just
 dumb it down with used to.

I had forgot to mention one other usage of used to:

WRONG: I used to not like indention but know i am very used to it
RIGHT: Previously i lamented forced indentation but i have since
grown quite accustomed to it

Also the usage of supposed to is rather foolish.

WRONG: We are supposed to write clean code but i am not used to that
RIGHT: We are required to write clean code however i am not accustom
to that way of thinking.

Gawd, sometimes i feel like i'm watching an episode of squidbillies
when i read the this list.






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


Re: Ten rules to becoming a Python community member.

2011-08-14 Thread rantingrick
On Aug 14, 5:01 pm, Dave Angel da...@ieee.org wrote:

 Interesting that when you complain about other's grammatical typos,
 you're so careless with your own.

 know - now
 i - I
 accustom - accustomed
 the this - this

 I'm inclined to ignore typos in emails except in the case where the
 intent is to abuse others.

My intent is NOT to abuse, but to enlighten. And you need to look up
the definition of typo because i am not complaining about typos. Typos
are accidents. Even the best of us suffer from accidents.

What i AM complaining about is the adoption of a collectively foolish
consistency. Used to and supposed to is the verbiage of children
and idiots. I am trying to break these people out of such foolish
loops. You should be thanking me instead of trolling my posts.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ten rules to becoming a Python community member.

2011-08-14 Thread rantingrick
On Aug 14, 7:56 pm, Steven D'Aprano steve
+comp.lang.pyt...@pearwood.info wrote:
 Chris Angelico wrote:
  I think you need to start a blog, Rick.
  You'd be easier to ignore.

 And yet, here you are, engaging him in conversation and feeding him the
 attention he craves :(

Yes, Steven loves rule # 2. Second only to the strawmen armies he has
built.

Kurtz: What do you call it when the assassins accuse the assassin?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow line break at operators

2011-08-13 Thread rantingrick
On Aug 12, 5:03 pm, Steven D'Aprano steve
+comp.lang.pyt...@pearwood.info wrote:

 Responding to Rick's standard {EDIT} posts
 is like wrestling with a {EDIT}
 [...]
 Save yourself a lot of aggravation and kill-file him now.

Kindly allow Walter E. Kurtz to shine some light on this situation:

 Pig after pig, cow after cow, village after village, army after
army. And they call me an assassin. What do you call it when the
assassins accuse the assassin? They lie.. they lie and we have to be
merciful for those who lie. Those nabobs. I hate them. How I hate
them...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow line break at operators

2011-08-13 Thread rantingrick
On Aug 12, 7:39 pm, Seebs usenet-nos...@seebs.net wrote:

 Well, that's the thing.

 In a case like:

         if foo:
                 if bar:
                         blah
         blah

 I notice that *NOTHING* lines up with if bar:.  And that affects me
 about the way unmatched brackets do.

For me, i believe it was a grave mistake to allow user defined
indention within a python module. Not only that, but allowing
indentation to be inconsistent (within the same module) not only
worse, it's insane!

I could have slightly understood giving people a choice of how many
indents to use however i cannot fathom the idiocy of allowing
inconsistent indentation within the same module! Although GvR is no
doubt a brilliant mind he keeps making the same mistakes over and over
again in the name of muti-stylism. ¡Ay, caramba!

Not that i find it *impossible* to read inconsistent indentation mind
you, but that i find it blasphemous to the name of consistency.
Programming languages MUST be consistent. Python should allow one and
only one obvious way to indent a block; whether it be by a single tab
char or by four spaces i don't care! But for crikey's sake pick one of
them and stick with it!!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow line break at operators

2011-08-13 Thread rantingrick
On Aug 12, 7:39 pm, Seebs usenet-nos...@seebs.net wrote:

 I was overjoyed when I saw that Ruby would let me write 1_048_576.

I'll have to admit that Ruby has a few very interesting ideas, this
being one of them. We all know how impossible it can be to eyeball
parse a very long number like this. Having the interpretor ignore
underscores in a number was very wise indeed!

However i really hate the fact that Ruby FORCES you to use OOP. I LOVE
OOP, however there are times when you just don't need that level of
machinery to solve a problem. A good example is when scripting an API.
Most times all you need is a few module level procedures and some
simple logic. Try that with Ruby, then try that with Python, you'll be
switching to Python in no time!

PS: And before any Matz lovers start complaining: Yes, i know you can
do procedural programming with ruby HOWEVER it suffers many pitfall
due to (1) Ruby's scoping issues and (2) Ruby's explicit module
declaration (which is more indirect than the first).

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


Re: allow line break at operators

2011-08-13 Thread rantingrick
On Aug 12, 7:39 pm, Seebs usenet-nos...@seebs.net wrote:

 Consider the hypothetical array syntax:

         a = [
             1,
             2
         b = [
             3,
             4

 This *bugs* me.  It's perfectly legible, and if you define it that way, it's
 unambiguous and everything, but... It bugs me.  I want beginnings to have
 an actual corresponding end.

It almost seems as if you have a valid point here until you consider
that conditionals and blocks are ridged structures that must be
defined under a strict set of syntactical rules with keywords and
indentation. Whereas the list, dict, set, and tuple absolutely MUST
have an explicit beginning AND an explicit end due to their free-form
nature. You could create some strict rules for defining X-literals
and remove any need for start and end tags however i see no need to do
so.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow line break at operators

2011-08-13 Thread rantingrick
On Aug 12, 4:06 pm, Seebs usenet-nos...@seebs.net wrote:
 On 2011-08-12, Chris Angelico ros...@gmail.com wrote:

  Why is left-to-right inherently more logical than
  multiplication-before-addition?

 I'd say it's certainly more Pythonic in a vacuum.
 Multiplication-before-addition, and all the related rules, require
 you to know a lot of special rules which are not visible in the
 code, and many of which have no real logical basis.  Left-to-right
 is, if nothing else, the way the majority of us read.

 The problem is that since everyone's used precedence before, not using
 it violates the principle of least astonishment.

And repeatedly propagating a foolish consistency is well, FOOLISH!

This problem invades every aspect of technology. Who was the idiot
that decided it was okay to close SOME html tag and NOT close others?
Since HTML is made to be read by machines why the hell would someone
knowingly induce disorder? Which then leads to needing more logic to
parse?

But even more insane is why HTML has been allowed to be so disorderly
for so long. Where is the need to be consistent? I tell you how to
solve this, you solve it with plagues. Plagues of syntax errors will
teach the unrighteous the err of their ways.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow line break at operators

2011-08-12 Thread rantingrick
On Aug 12, 1:34 am, Seebs usenet-nos...@seebs.net wrote:

 And part of this really is personal taste.  I *LIKE* having a matching outdent
 for everything.  I like to look at code and see
         blah
                 blah
                         blah
                 blah
         blah

 because then I know it's balanced.  If one of them is missing, *something is
 wrong*.

What is with you guys and this need to have your hand held to read
code. Out-dents are noise and nothing more. When you're driving on a
two lane highway that becomes one lane, would you forget to merge
(OUTDENT) simply because the merge sign was missing? If you did then
i would say you need to keep your eyes on the road (CODE) instead of
looking for signs on the side of the road. In other words; you need to
start acting like an intelligent agent instead of a zombie.

 In other language communities, when I find things about the language
 troublesome, I usually find people offering suggestions for ways to improve
 things, or workarounds, or acknowledging that, yes, that can be annoying.
 But for some reason, in this one, that's apparently against a local taboo.
 So instead of acknowledging that it is conceivably possible for people to
 prefer different things, people say things like oh, once you've done it a
 bit you'll realize how much better it is and then you'll love it.
 Condescending, smug, and, at least so far, *totally untrue* for me.

Well for indention there is no alternatives. There is either indent/
dendent, or suffer the syntax error.

 I am also weirded out by the claim that a Python which used braces would no
 longer be Python in any way, shape, or form.  If you were to make a C
 derivative which used indentation instead of braces (this should be trivial
 to do with a preprocessor), I can't imagine C programmers claiming it's
 not C.  Of course it's C; it has the C type system, the C operators, the
 C promotion rules, C linkage and scope and so on... That's C.  It's just a C
 variant which tweaks the punctuation.

Hmm, Python's exclusive use of indent/dedent for denoting blocks is
rather unique in a world of braces (barring a few other less known
languages). Removing that feature and replacing it with braces (or
tags or whatever) would change the language significantly!

Likewise allowing a directive like use braces = True would also be
detrimental to our code bases. A language must always strive to remove
ambiguities and multiplicity. Having more than one way to mark blocks
is insanity. You never want to induce more overhead than necessary
because such things are detrimental to work flow and language
evolution.

 If Python with braces wouldn't be Python at all, why on earth does the
 language even exist?  If all you want is indentation-which-matters, it's
 super easy to write a preprocessor for ANY language to do that, and you could
 have every last positive feature, benefit, or valuable trait of Python by
 doing that to any other language.

This statement leads me to believe you have very little experience
with the Python language. Python has many wonderful attributes and
design philosophies. Significant indentation is just ONE of many.

 Unless, of course, there are *other* things that are significant
 about Python.  In which case, a language which preserved all of
 those, but used braces, would still be a kind of Python after all.

I don't understand this need for braces. You yearn so badly to be
dominated by them. Is this a psychological disorder, a Helsinki
syndrome that you cannot shake? There is life after braces my friend,
and the future is bright!

 Long story short:  I think the dismissiveness and hostility I've seen from
 people in the Python community towards people who, for *whatever* reason,
 find the indentation-flow-control thing annoying, is not really helping the
 Python community win converts.  

As much as we love people getting on board we are not about to
sacrifice our strong beliefs in clean source code just so you and
other hardwired C programmers will come along. Indentation is at the
very heart of Pythons philosophy. A philosophy that breaks free from
decades old language design build on the detrimental ideals of multi-
stylism. Good languages do not care about your singularly instinctual
emotion needs for bondage, no, they care about productivity and
readability from a community perspective.

PS: I will admit that a few of our community members can be rather
acerbic at times.

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


Re: allow line break at operators

2011-08-12 Thread rantingrick
On Aug 12, 2:20 am, Chris Angelico ros...@gmail.com wrote:

 Pike is very [snip]
 Pike's purpose is [snip]
 you go to Pike[snip]

 I hope I make myself clear, Josephine?

The only thing that is clear to me is that you have a hidden agenda to
incorporate pike's functionality into Python -- and this is not the
first time!

Chris, this incessant babbling about pike this and pike that is
starting to get on my nerves. Why don't you go over to comp.lang.pike
and gush to them about how wonderful the language is.

PS: Although i give you brownie point for sucking up to GvR and the
community at large before hinting about Esox lucius greatness. Nice!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow line break at operators

2011-08-12 Thread rantingrick
On Aug 12, 11:33 am, Seebs usenet-nos...@seebs.net wrote:

 My brain has quirks.  Some people call them defects, some don't, but it
 really doesn't matter; there are things about which my brain is just plain
 unreliable and I rely moderately heavily on extra visual cues to reduce
 the frequency with which I get things wrong when skimming.

I think that really boils down to you refusing to open your eyes up to
new ways of doing things. You are clutching the past and it is taking
you down with it. Pry your lips from Ritchie's left teet and stop
slurping that brace milk; because it is polluting your mind!

  When you're driving on a
  two lane highway that becomes one lane, would you forget to merge
  (OUTDENT) simply because the merge sign was missing?

 No, because the *LANE BOUNDARIES* would move.

The lane boundaries will also move whilst reading code that uses the
indent/dedent paradigm. Are you honestly telling me that you will skip
over a four spaced dedent without seeing it however you can easily
spot a single closing brace and instantly know which corresponding
opener brace to which it referrers without looking, and counting, and
wasting time? Sorry, i just don't believe you.

 I propose we extend it to expression processing in general.  Instead
 of writing
         a = (x + y) * z
 let's just write
         a = (x + y * z

I'm glad you brought this up! How about this instead:

a = x + y * z

...where the calculation is NOT subject to operator precedence? I
always hated using parenthesis in mathematical calculations. All math
should resolve in a linear fashion. 3+3*2 should always be 12 and NOT
9!

 It's obvious that no one would have needed to introduce parentheses here
 unless they wanted to bind the + more closely than the *, so the ) is
 just noise and not needed.

I would even go as far to use a special set of brackets for linear
calculations before using only one, or playing the precedence game.

  As much as we love people getting on board we are not about to
  sacrifice our strong beliefs in clean source code just so you and
  other hardwired C programmers will come along.

 But you will happily insult people and call them names in order to
 keep them from having anything to listen to?

I am not trying to discredit you simply by disagreeing with you. I
have offered facts as to why significant indention is far superior to
braces and yet you continue to use the same emotionally charged babble
in your defense. When you offer some real facts then i will give then
just consideration, until then i will try to enlighten you of the
merits of significant indentation.

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


Re: PyWart: os.path needs immediate attention!

2011-08-02 Thread rantingrick
On Aug 1, 3:19 am, Teemu Likonen tliko...@iki.fi wrote:
 * 2011-07-30T10:57:29+10:00 * Steven D'Aprano wrote:

  Teemu Likonen wrote:
  Pathnames and the separator for pathname components should be
  abstracted away, to a pathname object.

  Been there, done that, floundered on the inability of people to work
  out the details.

 http://www.python.org/dev/peps/pep-0355/

 I'm very much a Lisp person and obviously got the idea of pathname
 objects from Common Lisp. Lazily I'm also learning Python too but at the
 moment I can't comment on the details of that PEP. Yet, generally I
 think that's the way to improve pathnames, not the rantinrick's.

This thread was intended to expose another PyWart and get the
community juices flowing. os.path is broken and cannot be repaired
because os.path was an improper API to begin with. The only way to
solve this problem is to introduce a new Path object.

A new Path object is the answer.

Some have said been there, done that with a sarcastic and defeatist
point of view. I say we need to re-visit the proposal of PEP-0355 and
hash out something quickly. We also need to realize that one day or
another this Path object is going to become reality and the longer we
drag our feet getting it implemented the more painful the transition
is going to be.

I feel Python community is in an awkward teenage stage at this point
not really sure of it's self or direction. Living only for today with
no ability to project the future and wasting too much time arguing
over minutiae. We need a collective wake-up-call in the form of a slap
on the face. We need to start making the hard choices necessary to
clean up this library.

Python3000 was only the beginning! ONLY THE BEGINNING!

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


PyWart: os.path needs immediate attention!

2011-07-29 Thread rantingrick

--
 Overview of Problems:
--

 * Too many methods exported.
 * Poor choice of method names.
 * Non public classes/methods exported!
 * Duplicated functionality.

--
 Proposed new functionality:
--

 * New path module will ONLY support one path sep! There is NO reason
to support more than one. When we support more than one path sep we
help to propagate multiplicity.We should only support the slash and
NOT the backslash across ALL OS's since the slash is more widely
accepted. If an OS does not have the capability to support only the
slash then that OS is not worthy of a Python builtin module. The users
of such OS will be responsible for managing their OWN os_legacy.path
module. We are moving forward. Those who wish to wallow in the past
will be left behind.

 * Introduce a new method named partition which (along with string
splitting methods) will replace the six methods basename, dirname,
split, splitdrive, splitunc, splittext. The method will return
a tuple of the path split into four parts: (drive, path, filename,
extension). This is the ONLY splitting method this module needs. All
other splits can use string methods.

--
 Expose of the Warts of current module:
--


~
 1. Too many methods
~

Follows is a list of what to keep and what to cull:

 + abspath
 + altsep
 - basename -- path.partition[-2]
 + commonprefix
 + curdir
 + defpath
 + devnull
 - dirname -- os.path.join(drive,path)
 + exists
 + expanduser
 + expandvars
 + extsep
 - genericpath -- should be private!
 + getatime
 + getctime
 + getmtime
 + getsize
 + isabs
 + isdir
 + isfile
 + islink
 + ismount
 + join
 - lexists -- duplicate!
 - normcase -- path = path.lower()
 - normpath -- should not need this!
 - os -- should be private!
 + pardir
 + pathsep
 + realpath
 + relpath
 + sep
 - split -- path.rsplit('/', 1)
 - splitdrive -- path.split(':', 1)
 - splitext -- path.rsplit('.')
 - splitunc -- Unix specific!
 - stat -- should be private!
 + supports_unicode_filenames -- windows specific!
 - sys -- should be private!
 + walk
 - warnings -- should be private!


~
 2. Poor Name Choices:
~

 * basename -- should be: filename
 * split -- split what?
 * splitext -- Wow, informative!

~
 3. Non Public Names Exposed!
~

 * genericpath
 * os
 * stat
 * sys
 * warnings


Note: i did not check the Unix version of os.path for this.

~
 4. Duplicated functionality.
~

 os.path.lexists.__doc__
'Test whether a path exists.  Returns False for broken symbolic links'
 os.path.exists.__doc__
'Test whether a path exists.  Returns False for broken symbolic links'

Should have been one method:
 os.path.exists(path, ignoreSymLnks=False)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: @PyNoobs: The Fundamental Five Built-in Functions, and Beyond!

2011-07-28 Thread rantingrick
On Jul 26, 9:53 pm, Terry Reedy tjre...@udel.edu wrote:
 On 7/26/2011 8:01 PM, rantingrick wrote:

  Most new user think that printing an object to stdout is all they'll
  ever need. However when you call print -- or sys.stdout.write(object)
  -- you are only seeing a friendly version of the object.

 This mostly applies to strings, which *do* have 2 printed versions.  It
 is occasionally very important for debugging string problems.

Actually you have to be careful of objects too. Consider this:

py import Tkinter
py root = Tkinter.Tk()
py print root
.
py print repr(root)
Tkinter.Tk instance at 0x02BDC4E0
py label = Tkinter.Label(root)
py print label
.46012656
py print repr(label)
Tkinter.Label instance at 0x02BE18F0

...as you can see, if someone overrides __str__ you can get some very
confusing return values from a naked print(obj) -- which simply calls
obj.__str__() under the covers.

  --
    5. id()
  --
  http://docs.python.org/py3k/library/functions.html#id
 
  [...}
 
 This is the most dangerous of the builtins, as it sometimes mislead
 newbies into 'discovering' non-existent 'bugs'. The main point is that
 the id of immutable objects is mostly an irrelevant implementation
 detail, while the id of mutables may be critical. Lists of lists is a
 particular area where id() is really useful.

Yes this one can cause some major confusion to newcomers. I wonder if
python should throw a warning anytime you call id() on an immutable
type.

py a = 12345
py id(a)
45313728
py b = 12345
py id(b)
45313728

That first call to id should have thrown a warning:

 Traceback (most recent call last):
   File pyshell#5, line 1, in module
 id(a)
 Warning: Comparing ids of immutable types is unreliable!

and an Exception if someone tries an assertion!

 py assert id(a) != id(b)

 Traceback (most recent call last):
   File pyshell#6, line 1, in module
 assert id(a) != id(b)
 Exception: Cannot compare immutable types!
-- 
http://mail.python.org/mailman/listinfo/python-list


PyWart: PEP8: a seething cauldron of inconsistencies.

2011-07-28 Thread rantingrick

I believe the current Python style guide is inconsistent. The author
again allowed his emotion to get in the way of logic. I will be
posting blocks of text from the PEP8 and commenting below them.

 --
 One of Guido's key insights is that code is read much more
 often than it is written.  The guidelines provided here
 are intended to improve the readability of code and make
 it consistent across the wide spectrum of Python code.  As
 PEP 20 [6] says, Readability counts.
 --

Yes but the style guide itself is contradictory!

 --
 A style guide is about consistency.  Consistency with this
 style guide is important.  Consistency within a project is
 more important. Consistency within one module or function
 is most important.
 --

Hmm, Yes. And CONSISTENCY within a style guide that promotes
CONSISTENCY should trump them all! However as we'll see shortly
CONSISTENCY has been sacrificed at the alter of fluffy feelings and
multi-style-ism.

 --
 But most importantly: know when to be inconsistent --
 sometimes the style guide just doesn't apply.  When in
 doubt, use your best judgment.
 --

WRONG! When in doubt be consistent! There should be one AND ONLY ONE
obvious way to do it! When we have multiple ways of doing the same
thing we induce an overhead into our work flows. Instead we need to
follow the zen; in other words, BE CONSISTENT!

 --
 Look at other examples and
 decide what looks best.  And don't hesitate to ask!
 --

NO, NO! Follow the community standards. NEVER make up your own. We
cannot keep propagating multiplicity or else we will drown in it! We
cannot have people just making up syntax for iterations can we? No!.
Likewise we cannot allow people to make up styles as they please.

 --
 Two good reasons to break a particular rule:

 (1) When applying the rule would make the code less
 readable, even for someone who is used to reading code
 that follows the rules.

 (2) To be consistent with surrounding code that also
 breaks it (maybe for historic reasons) -- although this is
 also an opportunity to clean up someone else's mess (in
 true XP style).
 --

Number two is the ONLY reason why ANYONE should not follow the style
guide to a T! However, code of this style should be shamed by the
community.

 --
 Use 4 spaces per indentation level.
 --

This should be the only acceptable indention level allowed by the
interpreter. All other indention should cast plagues of syntax errors
on the unrighteous.

 --
 For really old code that you don't want to mess up, you
 can continue to use 8-space tabs.
 --

NO! You should convert the code to 4 space tabs and move into the 21st
century. Stop living in the past. We must move forward... kicking and
screaming if necessary.

 --
 Tabs or Spaces?

 Never mix tabs and spaces.

 The most popular way of indenting Python is with spaces
 only.  The second-most popular way is with tabs only.
 Code indented with a mixture of tabs and spaces should be
 converted to using spaces exclusively.  When invoking the
 Python command line interpreter with the -t option, it
 issues warnings about code that illegally mixes tabs and
 spaces.  When using -tt these warnings become errors.
 These options are highly recommended!
 --

Here is another missed opportunity to force compliance of a style
convention. Mixing tabs and spaces should throw syntax errors! Is it
too much to ask that people at least choose one over the other? Sheez,
are we that afraid of offending them? Are these people emotional
basket cases riving with suicidal tendencies? *rolls-eyes* If they are
then the Python style guide is the LEAST of their problems.

 --
 Blank Lines

 Separate top-level function and class definitions with two
 blank lines.

 Method definitions inside a class are separated by a
 single blank line.
 --

This should be the law. Unfortunately many stdlib modules do not
follow this suggestion. In Python4000 i'm making it a syntax error to
include ANY blank lines in a func/meth body.

 

Re: How do I access IDLE in Win7

2011-07-27 Thread rantingrick
On Jul 27, 10:06 am, W. eWatson wolftra...@invalid.com wrote:
 It's been many months since I played with Python, and have forgotten how
 to bring up IDLE. If I simply click on a py file, I see what may be a
 dos window appear and quickly disappear.

Double-clicking a [py|pyw] file in windows will auto run the file
(considering you have not changed the association). So if you're
trying to edit the file you'll want to try something else.

 If I right-click on the file,
 and select IDLE, the same thing happens.

You mean Right-Click - Send-To-IDLE?

 If I go directly to All
 Programs, the same thing happens when I select IDLE.

You mean Start_Menu - All_Programs - PythonX.X - IDLE_(Python
GUI)? Yes typically that is how you'd run IDLE form a winders box.

If you want to edit a python script then first open an editor and then
navigate to the file. There is also a RightClick - Open-with-IDLE
option also but i prefer to navigate from my editor.

However it sounds like you may be experiencing a bug (or configuration
issue). Can you capture the dos error with the print screen button
and post it here? You'll have to be quick to catch it!

Also try to run IDLE from this path:
...\PythonXX\Lib\idlelib {double click PyShell.py}
-- 
http://mail.python.org/mailman/listinfo/python-list


PyWart: PEP8: A cauldron of inconsistencies.

2011-07-27 Thread rantingrick

I believe the current Python style guide is inconsistent. The author
again allowed hie emotion to get in the way of logic. I will be
posting blocks of text from the PEP8 and commenting below them.

 --
 One of Guido's key insights is that code is read much more
 often than it is written.  The guidelines provided here
 are intended to improve the readability of code and make
 it consistent across the wide spectrum of Python code.  As
 PEP 20 [6] says, Readability counts.
 --

Yes but this guide itself is contradictory Mr Van Rossum.

 --
 A style guide is about consistency.  Consistency with this
 style guide is important.  Consistency within a project is
 more important. Consistency within one module or function
 is most important.
 --

Hmm, Yes. And CONSISTENCY within a style guide that promotes
CONSISTENCY should trump them all! However as we'll see shortly
CONSISTENCY has been sacrificed at the alter of fluffy feelings and
multi-style-ism.

 --
 But most importantly: know when to be inconsistent --
 sometimes the style guide just doesn't apply.  When in
 doubt, use your best judgment.
 --

WRONG! When in doubt be consistent! There should be one AND ONLY ONE
obvious way to do it! When we have multiple ways of doing the same
thing we induce an overhead into our work flows. Instead we need to
follow the zen; in other words, BE CONSISTENT!

 --
 Look at other examples and
 decide what looks best.  And don't hesitate to ask!
 --

NO, NO! Follow the community standards. NEVER make up your own. We
cannot keep propagating multiplicity or else we will drown in it! We
cannot have people making up syntax for iterations can we? Likewise we
cannot allow people to make up styles.

 --
 Two good reasons to break a particular rule:

 (1) When applying the rule would make the code less
 readable, even for someone who is used to reading code
 that follows the rules.

 (2) To be consistent with surrounding code that also
 breaks it (maybe for historic reasons) -- although this is
 also an opportunity to clean up someone else's mess (in
 true XP style).
 --

Number two is the ONLY reason why ANYONE should not follow the style
guide to a T! However, code of this style should be shamed by the
community.

 --
 Use 4 spaces per indentation level.
 --

This should be the only acceptable indention level allowed by the
interpreter. All other indention should cast plagues of syntax errors
on the unrighteous.

 --
 For really old code that you don't want to mess up, you
 can continue to use 8-space tabs.
 --

NO! You should convert the code to 4 space tabs and move into the 21st
century. Stop living in the past. We must move forward... kicking and
screaming if necessary.

 --
 Tabs or Spaces?

 Never mix tabs and spaces.

 The most popular way of indenting Python is with spaces
 only.  The second-most popular way is with tabs only.
 Code indented with a mixture of tabs and spaces should be
 converted to using spaces exclusively.  When invoking the
 Python command line interpreter with the -t option, it
 issues warnings about code that illegally mixes tabs and
 spaces.  When using -tt these warnings become errors.
 These options are highly recommended!
 --

Here is another missed opportunity to force compliance of a style
convention. Mixing tabs and spaces should throw syntax errors! Is it
too much to ask that people at least choose one over the other? Sheez,
are we that afraid of offending them? Are these people emotional
basket cases riving with suicidal tendencies? *rolls-eyes* If they are
then the Python style guide is the LEAST of their problems.

 --
 Blank Lines

 Separate top-level function and class definitions with two
 blank lines.

 Method definitions inside a class are separated by a
 single blank line.
 --

This should be the law. Unfortunately many stdlib modules do not
follow this suggestion. In Python4000 i'm making it a syntax error to
include ANY blank lines in a func/meth body.

 

@PyNoobs: The Fundamental Five Built-in Functions, and Beyond!

2011-07-26 Thread rantingrick



 The Fundamental Five built-in functions

There are quite a few helpful built in functions provided to the
python programmer however in my mind five of them are the most
important to Python noobs. The fundamental five i call them. I
believe you should not do anything with Python until you are
completely familier with these five because most of the bugs and mis-
understanding a new user experiences can be solved by using these five
functions.


--
1. help()
--
http://docs.python.org/py3k/library/functions.html#help

The help function is by far the most important of all Python built
in functions. It is a gift handed down from the gods who reside at py-
dev so don't balk at it or you'll suffer plagues of exceptions. Unlike
other languages, Python has documentation built-in in the form of
docstrings and the help function will pull out as much or as little
info as you'd like from these do strings. No need to carry around
heavy books or hundreds of links to www tuts because everything you
need to know (reference wise) is available via the help function. Run
the help function and ye shall be enlightened!

--
 2. dir()
--
http://docs.python.org/py3k/library/functions.html#dir

Python has name spaces. Name spaces are awesome. Name spaces keep code
from clashing with other code. The dir() function will list the
currently defined names in the current namespace. If your getting
NameErrors check the name space with dir() function.

--
 3. repr()
--
http://docs.python.org/py3k/library/functions.html#repr

Most new user think that printing an object to stdout is all they'll
ever need. However when you call print -- or sys.stdout.write(object)
-- you are only seeing a friendly version of the object. You can
even control the return value in your own classes bu overriding the
obj.__str__() special method. This friendly version is sufficient most
of the time HOWEVER when debugging it can lead you to smash you head
on the keyboard repeatedly due to it's sometimes misleading nature. If
you need to get the true representation of an object then call...
repr(object).

--
 4. type()
--
http://docs.python.org/py3k/library/functions.html#isinstance

Ever had a TypeError? Ever had some object you were just sure was one
type but is not behaving like that type? Then check it's type for
Pete's sake! Even experienced programmers (of many languages) suffer
from TypeErrors (be them subtle or not) because the type of an object
cannot be inferred simply by looking at it's identifier. So when
something ain't right, skip the tripe, and check the type!

--
 5. id()
--
http://docs.python.org/py3k/library/functions.html#id

Ah yes, another source of frustration is the old identical twin
syndrome (or in the worst forms; multiplicity syndrome!). Yes, on the
surface that list of lists looks as if it contains unique elements
HOWEVER you keep getting strange results. How are you going to find
the problem? Hmm? Never fear my confused new friend, by comparing the
ids of two objects you can know if they are actually the same or
different. If the id is the same, the objects are the same.

--
Summary
--
These five functions are vital to debugging any python code or
understanding an API. You will be using these functions over and over
again, so the sooner you learn them the better!

==
 Extending The Five
==
Once you have mastered the five it is time to expand your horizons a
bit. The next group of functions will complete the circle of
introspection.
==
 * hasattr()
 * isintance()
 * issubclass()
 * callable()
 * super()
 * vars()
 * globals()
 * locals()

 * ascii()

==
General Built-in Functions by Group.
==

--
 Objects
--
Bulling an object:
 * delattr()
 * getattr()
 * setattr()

Setting the rules:
 * staticmethod()
 * classmethod()
 * property()

--
 Numbers and Math
--
 * abs()
 * 

Re: Strings show as brackets with a 'u'.

2011-07-26 Thread rantingrick
On Jul 25, 3:00 am, Ulrich Eckhardt ulrich.eckha...@dominolaser.com
wrote:
 Chris Angelico wrote:

  [snip]

 You just gave the OP a fish, he provided a
 valuable advise on fishing itself.

I always believed the best way to teach someone is not to give them a
direct answer. No. Instead i like to offer clues so that the person
can utilize his own problem solving skills to find the answer. Because
the most important skill a person can have in the programming field is
the ability to solve complex problems by breaking them down into their
smallest units; tackling each unit; and finally assembling the puzzle
in a cohesive and intelligent manner.

Anyway the OP may want to check out my recent thread regarding
Python's Built-in Functions.
http://groups.google.com/group/comp.lang.python/browse_thread/thread/f419d4e11f27882e?hl=en#

--
rr
http://sites.google.com/site/thefutureofpython/

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


Re: Validating Entry in tkinter

2011-07-25 Thread rantingrick
On Jul 25, 2:08 pm, Peter Otten __pete...@web.de wrote:
 Terry Reedy wrote:
  On 7/25/2011 8:31 AM, Peter Otten wrote:
  Saul Spatz wrote:
  is it possible to set an onkey handler, that will pass on
  valid keys?

 With validatecommand you can have tkinter provide the string that is being
 inserted:

Yes but it's messy and requires knowledge of Tcl! We to keep our code
bases as Pythonic as possible.

 If you need something more specific you'd probably have to bind the
 KeyPress event to a custom handler:

Exactly!

If you compare the code of the two approaches you'll see that the
python approach is more readable and does not export any magic
behind the scenes. By binding the KeyPress event and handling it in
some derived class people who are not familiar with Tcl\Tk can read
the code (and change it to suit their needs). The next best
alternative would be to extend Tk.Entry with a pythonic wrapper for
this functionality.

MORAL: Sometimes you are forced to export these things but in this
case i would argue that readability counts; so keep it in Python!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Validating Entry in tkinter

2011-07-24 Thread rantingrick
On Jul 24, 7:11 pm, Saul Spatz saul.sp...@gmail.com wrote:

 Can one do something like this in tkinter?
‡

(1) First of all what exactly do you wish return?
 * an integer
 * a float
 * something else?

(2) Is this input part of a modal or non-modal interface?

For me, input validation should happen in *real* time and NOT after
the fact. For instance; if you have two entrys forms and a button in
your GUI like below...

 +--+
 | Tk | X | |
 +--+
 |  |
 |  Value1: [  ]|
 |  Value2: [  ]|
 |  |
 |   [Calculate]|
 '--'

... and your validator only checks the contents of Value1 and
Value2 AFTER the user presses the Calculate button then
congratulations because you have just created an unintuitive GUI
design. Instead, your entry widgets should have been filtering the key-
presses so that it would be impossible to enter anything but an
integer or float or whatever you want. Running a validater after the
fact is an anti pattern.

It is not very difficult to subclass a tk.Entry widget and create some
validation/filtering logic. However it would be helpful if you could
be a wee bit more specific about your validation needs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert '165.0' to int

2011-07-23 Thread rantingrick

On Jul 23, 1:53 am, Frank Millman fr...@chagford.com wrote:
--
 The problem with that is that it will silently ignore any non-zero
 digits after the point. Of course int(float(x)) does the same, which I
 had overlooked.
--

Wait a minute; first you said all you wanted was to cast string
floats to integers NOW your changing the rules.

--
 I do not expect any non-zero digits after the point, but if there are,
 I would want to be warned, as I should probably be treating it as a
 float, not an int.
--
Then the solution is a try:except.

py def castit(value):
... try:
... v = int(value)
... return v
... except ValueError:
... return float(value)
...
py castit('165')
165
py castit('165.0')
165.0
py castit('165.333')
165.333
py castit('3.3')
3.3

--
 To recap, the original problem is that it would appear that some third-
 party systems, when serialising int's into a string format, add a .0
 to the end of the string. I am trying to get back to the original int
 safely.
--

But you also said you wanted floats too, i am confused??

--
 The ideal solution is the one I sketched out earlier - modify python's
 'int' function to accept strings such as '165.0'.
--

NO! You create your OWN casting function for special cases.

PythonZEN: Special cases aren't special enough to break the rules.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to customise math.sqrt(x) for some x?

2011-07-23 Thread rantingrick
On Jul 16, 3:35 am, Steven D'Aprano steve
+comp.lang.pyt...@pearwood.info wrote:
 I have a custom object that customises the usual maths functions and
 operators, such as addition, multiplication, math.ceil etc.

 Is there a way to also customise math.sqrt? I don't think there is, but I
 may have missed something.

Hmm, this question should win ambiguous award of the year. Here, allow
me to answer by proxy.


 Ambiguos Caller Sketch

SCENE: (A car owner calls a custom body shop to request work on his
car)
SHOP: Custom Car Works, how may we help you?
OWNER: Hello sir. I would like to customize my car.
SHOP: Sure. What kind of car is it exactly?
OWNER: Well i would say it's a normal car.
SHOP: Okay. What size engine does it have?
OWNER: I would say it's a fairy large engine.
SHOP: Interesting. So what kind of work are you needing?
OWNER: Something custom because i want it to look very customized.
SHOP: Well Sir we are after all a CUSTOM shop! *rolls-eyes*
OWNER: Great, because i need some custom work!
SHOP: Okay Sir, would you like us to PAINT your car?
OWNER: Sure, that would be great.
SHOP: Okay, so what color should we PAINT your car?
OWNER: A light color would be fine.
SHOP: I see. I think we can handle this job for you just fine however
I just have one more question.
OWNER: Yes...
SHOP: Tell me, does this sound like a phone hanging up? *click*
OWNER: Yes.
...
OWNER: Hello?
...
OWNER: Are you there?


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


Re: Strings show as brackets with a 'u'.

2011-07-23 Thread rantingrick
On Jul 23, 7:33 pm, goldtech goldt...@worldpost.com wrote:

  n
 [u'174']

 Probably newbie question but not sure how suppress the brackets and
 the 'u' ? I assume pyhon is telling me it's a unicode string in the n
 variable.

Try type(n) and see what happens. Then report back. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inconsistencies between zipfile and tarfile APIs

2011-07-22 Thread rantingrick
On Jul 22, 12:05 am, Corey Richardson kb1...@aim.com wrote:

   from archive import ZipFile, TarFile
   zf = ZipFile(path, *args)
   tf = TarFile(path, *args)

 I have nothing to do this weekend, I might as well either write my own or
 twist around the existing implementations in the hg repo.

My hat is off to you Mr. Richardson. I've even considered creating my
own clean versions of these two modules, because heck, it is not that
difficult to do! However we must stop fixing these warts on a local
level Corey. We MUST clean up this damn python stdlib once and for
all.

I am willing and you are willing; that's two people. However, can we
convince the powers that be to upgrade these modules? Sure, if we get
enough people shouting for it to happen they will notice. So come on
people make your voices heard. Chime in and let the devs know we are
ready to unite and tackle these problems in our stdlib.

What this community needs (first and foremost) is some positive
attitudes. If you don't want to write the code fine. But at least
chime in and say... Hey guys, that's a good idea! I would like to see
some of these APIs cleaned up too. good luck! +1

Now, even if we get one hundred people chanting... Yes, Yes, Fix This
Mess!... i know Guido and company are going to frown because of
backwards incompatibility. But let me tell you something people, the
longer we put off these changes the more painful they are going to
be.

Python 3000 would have been the perfect time to introduce a more
intuitive and unified zip/tar archive module however that did not
happen. So now we need to think about adding a duplicate module
archive.py and deprecating zipfile.py and tarfile.py. We can remove
the old modules when Python 4000 rolls out.

That's just step one people, we have a long way to go!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inconsistencies between zipfile and tarfile APIs

2011-07-22 Thread rantingrick
On Jul 22, 12:45 am, Terry Reedy tjre...@udel.edu wrote:
 On 7/22/2011 12:48 AM, rantingrick wrote:
  On Jul 21, 11:13 pm, Corey Richardsonkb1...@aim.com  wrote:

 Hmm. Archives are more like directories than files. Windows, at least,
 seems to partly treat zipfiles as more or less as such.

Yes but a zipfile is just a file not a directory. This is not the
first time Microsoft has mislead people you know. ;-)

 Certainly, 7zip
 present a directory interface. So opening a zipfile/tarfile would be
 like opening a directory, which we normally do not do. On the other
 hand, I am not sure I like python's interface to directories that much.

I don't think we should make comparisons between applications and
API's.

 It would be more sensible to open files within the archives. Certainly,
 it would be nice to have the result act like file objects as much as
 possible.

Well you still need to start at the treetop (which is the zip/tar
file) because lots of important information is exposed at that level:

 * compressed file listing
 * created, modified times
 * adding / deleting
 * etc.

I'll admit you could think of it as a directory but i would not want
to do that. People need to realize that tar and zip files are FILES
and NOT folders.

 Seaching open issues for 'tarfile' or 'zipfile' returns about 40 issues
 each. So I think some people would care more about fixing bugs than
 adjusting the interfaces. Of course, some of the issues may be about the
 interface and increasing consistency where it can be done without
 compatibility issues.

Yes i agree! If we can at least do something as meager as this it
would be a step forward. However i still believe the current API is
broken beyond repair so we must introduce a new archive module.
That's my opinion anyway.

 However, I do not think there are any active
 developers focued on those two modules.

We need some fresh blood infused into Python-dev. I have been trying
to get involved for a long time. We as a community need to realize
that this community is NOT a homogeneous block. We need to be a little
more accepting of new folks and new ideas. I know this language would
evolve much quicker if we did.

  Unfortunately i know what the powers that be are going to say about
  fixing this wart.

  PTB: Sorry we cannot break backwards compatibility

 Do you propose we break compatibility more than we do? You are not the
 only Python ranter. People at Google march into Guido's office to
 complain instead of posting here.

Well, i do feel for Guido because i know he's taking holy hell over
this whole Python 3000 thing. If you guys don't remember i was a
strong opponent of almost all the changes a few years ago (search the
archives). However soon after taking a serious look at the changes
and considering the benefits i was convinced. I believe we are moving
in the correct direction with the language HOWEVER the library is
growing stale by the second. I want to breathe new life into this
library and i believe many more people like myself exist but they
don't know how to get involved. I can tell everyone who is listening
the easiest first step is simply to speak up and make a voice for
yourself. Don't be afraid to state your opinions. You can start right
now by chiming in on this thread. Anybody is welcome to offer opinions
no matter what experience level.

  Rick: But what about Python 3000?
  PTB:  Oh, well, umm, lets see. Well that was then and this is now!

 The changes made for 3.0 were more than enough for some people to
 discourage migration to Py3. And we *have* made additional changes
 since. So the resistance to incompatible feature changes has increased.

Yes i do understand these changes have been very painful for some
folks (me included). However there is only but one constant in this
universe and that constant is change. I believe we can improve many of
these API's starting with zip/tar modules. By the time Python 4000
gets here (and it will be much sooner than you guys realize!) we need
to have this stdlib in pristine condition. That means:

 * Removing style guide violations.
 * Removing inconsistencies in existing API's.
 * Making sure doc strings and comments are everywhere.
 * Cleaning up the IDLE library (needs a complete re-write!)
 * Cleaning up Tkinter.
 * And more

Baby steps are the key to winning this battle. We hit all the easy
stuff first (doc-strings and style guide) and save the painful stuff
for Python 4000. Meanwhile we introduce new modules and deprecate the
old stuff. However we need to start the python 4000 migration now. We
cannot keep putting off what should have already been done in Python
3000.

  Maybe i can offer a solution. A NEW module called archive.py (could
  even be a package!) which exports both the zip and tar file classes.
  However, unlike the current situation this archive module will be
  consistent with it's API.

 Not a bad idea. Put it on PyPI and see how much support you can get.

Thanks, I might just do that!
-- 
http

Re: Inconsistencies between zipfile and tarfile APIs

2011-07-22 Thread rantingrick
On Jul 22, 3:26 am, Lars Gustäbel l...@gustaebel.de wrote:

 There is a reason why these two APIs are different. When I wrote tarfile
 zipfile had already been existing for maybe 8 years and I didn't like its
 interface very much. So, I came up with a different one for tarfile that in my
 opinion was more general and better suited the format and the kind of things I
 wanted to do with it. In the meantime the zipfile API got a lot of attention
 and some portions of tarfile's API were ported to zipfile.

Well i'll admit that i do like like the tarfile's API much better; so
kudos to you kind sir.

  *COMMENT*
  As you can see, the tarfile modules exports an open function and
  zipfile does not. Actually i would prefer that neither export an open
  function and instead only expose a class for instantion.

 So that is your preference.

WWrong! It is more that just a MERE preference. Tarfile and zipfile
are BOTH archive modules and as such should present a consistent API.
I really don't care so much about the actual details AS LONG AS THE
APIs ARE CONSISTENT!

  *COMMENT*
  Since a zipfile object is a file object then asking for the tf object
  after the object after the file is closed should show a proper
  message!

 It is no file object.

Then why bother to open and close it like a file object? If we are not
going to treat it as a file object then we should not have API methods
open and close.

  *COMMENT*
  Tarfile is missing the attribute fp and instead exposes a boolean
  closed. This mismatching API is asinine! Both tarfile and zipfile
  should behave EXACTLY like file objects

 If tarfile and zipfile
 objects behave EXACTLY like file objects, what does the read() method 
 return?
 What does seek() do? And readline()?

I am not suggesting that these methods become available. What i was
referring to is the fact that the instance does not return its current
state like a true file object would. But just for academic sake we
could apply these three methods in the following manner:

 * read() - extract the entire archive.
 * readline() - extract the N'ith archive member.
 * seek() - move to the N'ith archive member.

Not that i think we should however.

 What do you prove when you say that tarfile has no fp attribute?

My point is that the API's between tarfile and zipfile should be
consistent. fp is another example of inconsistency. If we are going
to have an fp method in one, we should have it in the other.

  *COMMENT*
  As you can see, unlike tarfile zipfile cannot handle a passed path.

 Hm, I don't know what you mean.

Sorry that comment was placed in the wrong position. I also eulogizer
for sending the message three times; it seems my finger was a little
shaky that night. What i was referring to is that tarfile does not
allow a path to be passed to the constructor whereas zipfile does:

  import tarfile, zipfile
  tf = tarfile.TarFile('c:\\tar.tar')
 Traceback (most recent call last):
   File pyshell#1, line 1, in module
 tf = tarfile.TarFile('c:\\tar.tar')
   File C:\Python27\lib\tarfile.py, line 1572, in __init__
 self.firstmember = self.next()
   File C:\Python27\lib\tarfile.py, line 2335, in next
 raise ReadError(str(e))
 ReadError: invalid header
  zf = zipfile.ZipFile('C:\\zip.zip')
  zf
 zipfile.ZipFile instance at 0x02C6CE18

  zf.namelist() - tf.getnames()
  zf.getinfo(name) - tf.getmenber(name)
  zf.infolist() - tf.getmembers()
  zf.printdir() - tf.list()

  *COMMENT*
  Would it have been too difficult to make these names match? Really?

 As I already stated above, I didn't want to adopt the zipfile API because I
 found it unsuitable. So I came up with an entirely new one. I thought that
 being incompatible was better than using an API that did not fit exactly.

I agree with you. Now if we can ONLY change the zipfile API to match
then we would be golden!

  PS: I will be posting more warts very soon. This stdlib is a gawd
  awful mess!

 I do not agree. Although I come across one or two odd things myself from time
 to time, I think the stdlib as a whole is great, usable and powerful.

And that's why we find ourselves in this current dilemma. This stdlib
IS a mess and yours and everyone else's denials about it is not
helping the situation.

 The stdlib surely needs our attention. Instead of answering your post, I 
 should
 have been writing code and fixing bugs ...

Will you be starting with the zipfile API migration?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inconsistencies between zipfile and tarfile APIs

2011-07-22 Thread rantingrick
On Jul 22, 3:49 am, Lars Gustäbel l...@gustaebel.de wrote:

 One could get the impression that you are leading a grass-roots movement
 fighting a big faceless corporation. Instead, what you're dealing with is this
 warm and friendly Python community you could as well be a part of if you are a
 reasonable guy and write good code.

Sometimes i do feel as if i am fighting against an evil empire. I am a
reasonable guy and i do write -good-, no excellent code.

 Yeah, great. Please write code. Or a PEP.

I am not about to just hop through all the hoops of PEP and PEP8 code
just to have someone say Sorry, we are not going to include your
code. What i want at this point is to get feedback from everyone
about this proposed archive.py module. Because unlike other people, i
don't want to ram MY preferred API down others throats.

Step one is getting feedback on the idea of including a new archive
module. Step two is hammering out an acceptable API spec. Step three
is is actually writing the code and finally getting it accepted into
the stdlib.

Not only do i need feedback from everyday Python scripters, i need
feedback from Python-dev. I even need feedback from the great GvR
himself! (maybe not right away but eventually).

  What this community needs (first and foremost) is some positive
  attitudes. If you don't want to write the code fine. But at least
  chime in and say... Hey guys, that's a good idea! I would like to see
  some of these APIs cleaned up too. good luck! +1

 +1

Thank you! Now, can you convince your comrades at pydev to offer their
opinions here also? Even if all they do is say +1.

  Now, even if we get one hundred people chanting... Yes, Yes, Fix This
  Mess!... i know Guido and company are going to frown because of
  backwards incompatibility. But let me tell you something people, the
  longer we put off these changes the more painful they are going to
  be.

 And backwards compatibility is bad why? Tell me, what exactly is your view
 towards this? Should there be none?

First let me be clear that backwards-compatibility (BC) is very
important to any community. We should always strive for BC. However
there is no doubt we are going to make mistakes along the way and at
some point SOME APIs will need to be broken in the name of consistency
or some other important reason.

As i've said before Py3000 would have been the PERFECT opportunity to
fix this broken API within the current zipfile and tarfile modules.
Since that did not happen, we must now introduce a new module
archive.py and deprecate the zip and tar modules immediately. We
shall remove them forever in Python4000.

If you guys think we are done breaking BC,  you are in for big
surprises! Py3000 was just the beginning of clean-ups.  Py4000 is
going to be a game changer! And when we finally get to Py4000 and
remove all these ugly warts python is going to be a better language
for it. Mark my words people!

 archive.py is no new idea. Unfortunately, to this day, nobody had the time to
 come up with an implementation.

It's time to change;
Can't stay the same;
Rev-o-lu-tion is MY name!

We can never become complacent and believe we have reached perfection
because we never will.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use self.vars in class.method(parameters, self.vars)

2011-07-22 Thread rantingrick
On Jul 22, 10:43 am, bruno.desthuilli...@gmail.com
bruno.desthuilli...@gmail.com wrote:

 class names should start with an uppercase letter:

WRONG! Class identifiers should use the capwords convention

 * class Foo
 * class FooBar
 * class FooBarBaz

--
 PEP8.Naming_Conventions.Class_Names
--
Almost without exception, class names use the CapWords convention.
Classes for internal use have a leading underscore in addition.
--

Make sure to follow this directive to a T because if you don't, i
can assure you that you will regret it! I would actually change
Almost without exception to WITHOUT EXCEPTION myself. Actually in
RickPy4000 naming conventions are going to be enforced -- follow them
or die of exceptions.


*Case in point:*
Some folks refuse to cap all words because they think some words
are actually a single compound word. And in the real world they are
correct but in the case sensitve world of programming this can bite
you in the arse later.

Consider:
 class Messagebox
 class Listview
 class Combobox
 class ScrolledTextbox

Now later on when you are writing some code you cannot remember which
words you capped and which you did NOT cap. Best thing to do is ALWAYS
cap every word. In other words, be consistent!
 class MessageBox
 class ListView
 class ComboBox
 class ScrolledTextBox

*school-bell-rings*

PS: Someone needs to create links in the PEP for faster navigation to
topic of interest OR we need to create a new module called
styleguide.py

 import styleguide
 styleguide.naming_conventions('class')
Almost without exception, class names use the CapWords convention.
Classes for internal use have a leading underscore in addition.

PEP8: http://www.python.org/dev/peps/pep-0008/

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


Re: Convert '165.0' to int

2011-07-22 Thread rantingrick
On Jul 22, 7:42 am, Hrvoje Niksic hnik...@xemacs.org wrote:
 Frank Millman fr...@chagford.com writes:
  int(float(x)) does the job, and I am happy with that. I was just
  asking if there were any alternatives.

 int(float(s)) will corrupt integers larger than 2**53, should you ever
 need them.  int(decimal.Decimal(s)) works with numbers of arbitrary
 size.

Correct!

 '{0:,.0f}'.format(2**53)
'9,007,199,254,740,992'

That's nine-quadrillion people! Only for galactic measurements or
microscopic reasons would you need such large numbers.

PS: GAWD i love that new string format function!

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


Re: Convert '165.0' to int

2011-07-22 Thread rantingrick
On Jul 22, 2:32 pm, rantingrick rantingr...@gmail.com wrote:
  '{0:,.0f}'.format(2**53)
 '9,007,199,254,740,992'

Would have been better to say

 '{0:,}'.format(2**53)
'9,007,199,254,740,992'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use self.vars in class.method(parameters, self.vars)

2011-07-22 Thread rantingrick
On Jul 22, 2:00 pm, John Gordon gor...@panix.com wrote:

 Why did you say he (Bruno) was wrong?


I'll admit my yelling the word WRONG may have been interpreted as me
suggesting that bruno was completely wrong. Bruno is correct about all
class identifiers starting with a capital letter HOWEVER if he just
stops at that point and does not explain the CapWords convention
lots of people may start down the road of a foolish consistency.

My chastisement of Bruno was only on the grounds of him failing to
offer the required amount of information to a new python programmer.
We should ALWAYS remove any ambiguities from our statements to new
users AND we should always link to the PEP8 when these type of style
questions come up.

It is SO very important that WE as a community are consistent in our
syntactical conventions. For me PEP8 does not go far enough and very
soon i will draft a PyWart Expose concerning the matter.

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


Re: Can someone help please

2011-07-22 Thread rantingrick
On Jul 21, 12:02 pm, Gary woody...@sky.com wrote:

--
 total = ' '
 os.chdir('/home/woodygar/Desktop/Docs')
 for i in os.listdir('.'):
--
i was a bad local var choice here! i and x are typically reserved to
represent integer indexes in local loop scope whilst iterating over a
container object. Likewise y and z are meant to represent the next
levels of indexes. However when looping over a list of strings use
something more appropriate like:

for filename in os.listdir('.'):
do_something_with(filename)

--
    if '.txt' in i:
--

No, no, don't do that! Do if str.endswith('.txt') instead. Or use the
os.path methods.

--
      f = open(i, 'r')
      total += f.read()
      f.close()
--

Two bad things happening here;

(1.) Need to catch exceptions.

try:
f = open(i, 'r')
total += f.read()
except IOERROR:
freak_out()
else:
f.close()

(2.) NEVER concatenate a string with += in a loop! Instead load the
strings into a list and then use ''.join(lst) method on the list.

 filetext = \
This is line one
this is line two

this is line four\

 lst = []
 for line in filetext.splitlines():
lst.append(line)
 lst
['This is line one', 'this is line two', '', 'this is line four']
 '\n'.join(lst)
'This is line one\nthis is line two\n\nthis is line four'
 print '\n'.join(lst)
This is line one
this is line two

this is line four



--
 message = \
 Subject: %s
 %s

 % (SUBJECT,total)
--

Use the new format spec over the old string interpolation if available
in your version of python.

MSG = 
Subject: {0}
{1}

MSG.format(SUBJECT,total)


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


Re: PEP 8 and extraneous whitespace

2011-07-21 Thread rantingrick
On Jul 21, 1:46 pm, Andrew Berg bahamutzero8...@gmail.com wrote:
 [snip PGP noise!]
 On 2011.07.21 01:32 PM, Thomas Jollans wrote:
 So, the PEP says: do not align operators. End of story.

 I'm pretty sure that colons, commas and equals signs are not operators.

'au contraire mon frere'.

Colons in a dictionary are assignment operators! The colon tells
Python to assign a value to a key. Likewise for commas which separate
values in containers. And of all things; YES, an equals sign IS most
assuredly an assignment operator.

 [snip MORE PGP noise!]

Lining up columns the way you propose is a major headache; as has been
pointed out. And i find it much less readable myself. Consistency is
the Key; remember? Consistency is not just a singular term applied
only to intelligent agents; no! It can just as well apply to
collective behavior consistency.

The fact remains: the chances of scanning across an empty void and
finding the correct row diminish exponentially by the the width of
said void (amount of space between columns)


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


[PyWart 1001] Inconsistencies between zipfile and tarfile APIs

2011-07-21 Thread rantingrick

I may have found the mother of all inconsitency warts when comparing
the zipfile and tarfile modules. Not only are the API's different, but
the entry and exits are differnet AND zipfile/tarfile do not behave
like proper file objects should.

 import zipfile, tarfile
 import os
 os.path.exists('C:\\zip.zip')
True
 os.path.exists('C:\\tar.tar')
True
 tarfile.is_tarfile('C:\\tar.tar')
True
 zipfile.is_zipfile('C:\\zip.zip')
True
 ZIP_PATH = 'C:\\zip.zip'
 TAR_PATH = 'C:\\tar.tar'

--
1. Zipfile and tarfile entry exit.
--
 zf = zipfile.open(ZIP_PATH)

Traceback (most recent call last):
  File pyshell#12, line 1, in module
zf = zipfile.open(ZIP_PATH)
AttributeError: 'module' object has no attribute 'open'
 tf = tarfile.open(TAR_PATH)
 tf
tarfile.TarFile object at 0x02B3B850
 tf.close()
 tf
tarfile.TarFile object at 0x02B3B850

*COMMENT*
As you can see, the tarfile modules exports an open function and
zipfile does not. Actually i would prefer that neither export an open
function and instead only expose a class for instantion.

*COMMENT*
Since a zipfile object is a file object then asking for the tf object
after the object after the file is closed should show a proper
message!

 tf = tarfile.TarFile(TAR_PATH)
Traceback (most recent call last):
  File pyshell#72, line 1, in module
tf = tarfile.TarFile(TAR_PATH)
  File C:\Python27\lib\tarfile.py, line 1572, in __init__
self.firstmember = self.next()
  File C:\Python27\lib\tarfile.py, line 2335, in next
raise ReadError(str(e))
ReadError: invalid header
 tf = tarfile.TarFile.open(TAR_PATH)
 tf
tarfile.TarFile object at 0x02C251D0
 tf.fp
Traceback (most recent call last):
  File pyshell#75, line 1, in module
tf.fp
AttributeError: 'TarFile' object has no attribute 'fp'
 tf
tarfile.TarFile object at 0x02C251D0
 tf.close()
 tf
tarfile.TarFile object at 0x02C251D0
 tf.fileobj
bz2.BZ2File object at 0x02C24458
 tf.closed
True

*COMMENT*
Tarfile is missing the attribute fp and instead exposes a boolean
closed. This mismatching API is asinine! Both tarfile and zipfile
should behave EXACTLY like file objects

 f = open('C:\\text.txt', 'r')
 f.read()
''
 f
open file 'C:\text.txt', mode 'r' at 0x02B26F98
 f.close()
 f
closed file 'C:\text.txt', mode 'r' at 0x02B26F98

--
2. Zipfile SPECIFIC entry exit
--
 zf
zipfile.ZipFile instance at 0x02B2C6E8
 zf.fp
 zf = zipfile.ZipFile(ZIP_PATH)
 zf
zipfile.ZipFile instance at 0x02B720A8
 zf.fp
open file 'C:\zip.zip', mode 'rb' at 0x02B26F98
 zf.close()
 zf
zipfile.ZipFile instance at 0x02B720A8
 zf.fp
 print repr(zf.fp)
None

*COMMENT*
As you can see, unlike tarfile zipfile cannot handle a passed path.

--
 3. Zipfile and Tarfile obj API differences.
--

zf.namelist() - tf.getnames()
zf.getinfo(name) - tf.getmenber(name)
zf.infolist() - tf.getmembers()
zf.printdir() - tf.list()

*COMMENT*
Would it have been too difficult to make these names match? Really?

--
 4. Zipfile and Tarfile infoobj API differences.
--

zInfo.filename - tInfo.name
zInfo.file_size - tInfo.size
zInfo.date_time - tInfo.mtime

*COMMENT*
Note the inconsistencies in naming conventions of the zipinfo methods.

*COMMENT*
Not only is modified time named different between zipinfo and tarinfo,
they even return completely different values of time.

--
 Conclusion:
--
It is very obvious that these modules need some consistency between
not only themselves but also collectively. People, when emulating a
file type always be sure to emulate the built-in python file type as
closely as possible.

PS: I will be posting more warts very soon. This stdlib is a gawd
awful mess!
-- 
http://mail.python.org/mailman/listinfo/python-list


[PyWart 1001] Inconsistencies between zipfile and tarfile APIs

2011-07-21 Thread rantingrick

I may have found the mother of all inconsitency warts when comparing
the zipfile and tarfile modules. Not only are the API's different, but
the entry and exits are differnet AND zipfile/tarfile do not behave
like proper file objects should.

 import zipfile, tarfile
 import os
 os.path.exists('C:\\zip.zip')
True
 os.path.exists('C:\\tar.tar')
True
 tarfile.is_tarfile('C:\\tar.tar')
True
 zipfile.is_zipfile('C:\\zip.zip')
True
 ZIP_PATH = 'C:\\zip.zip'
 TAR_PATH = 'C:\\tar.tar'

--
1. Zipfile and tarfile entry exit.
--
 zf = zipfile.open(ZIP_PATH)

Traceback (most recent call last):
  File pyshell#12, line 1, in module
zf = zipfile.open(ZIP_PATH)
AttributeError: 'module' object has no attribute 'open'
 tf = tarfile.open(TAR_PATH)
 tf
tarfile.TarFile object at 0x02B3B850
 tf.close()
 tf
tarfile.TarFile object at 0x02B3B850

*COMMENT*
As you can see, the tarfile modules exports an open function and
zipfile does not. Actually i would prefer that neither export an open
function and instead only expose a class for instantion.

*COMMENT*
Since a zipfile object is a file object then asking for the tf object
after the object after the file is closed should show a proper
message!

 tf = tarfile.TarFile(TAR_PATH)
Traceback (most recent call last):
  File pyshell#72, line 1, in module
tf = tarfile.TarFile(TAR_PATH)
  File C:\Python27\lib\tarfile.py, line 1572, in __init__
self.firstmember = self.next()
  File C:\Python27\lib\tarfile.py, line 2335, in next
raise ReadError(str(e))
ReadError: invalid header
 tf = tarfile.TarFile.open(TAR_PATH)
 tf
tarfile.TarFile object at 0x02C251D0
 tf.fp
Traceback (most recent call last):
  File pyshell#75, line 1, in module
tf.fp
AttributeError: 'TarFile' object has no attribute 'fp'
 tf
tarfile.TarFile object at 0x02C251D0
 tf.close()
 tf
tarfile.TarFile object at 0x02C251D0
 tf.fileobj
bz2.BZ2File object at 0x02C24458
 tf.closed
True

*COMMENT*
Tarfile is missing the attribute fp and instead exposes a boolean
closed. This mismatching API is asinine! Both tarfile and zipfile
should behave EXACTLY like file objects

 f = open('C:\\text.txt', 'r')
 f.read()
''
 f
open file 'C:\text.txt', mode 'r' at 0x02B26F98
 f.close()
 f
closed file 'C:\text.txt', mode 'r' at 0x02B26F98

--
2. Zipfile SPECIFIC entry exit
--
 zf
zipfile.ZipFile instance at 0x02B2C6E8
 zf.fp
 zf = zipfile.ZipFile(ZIP_PATH)
 zf
zipfile.ZipFile instance at 0x02B720A8
 zf.fp
open file 'C:\zip.zip', mode 'rb' at 0x02B26F98
 zf.close()
 zf
zipfile.ZipFile instance at 0x02B720A8
 zf.fp
 print repr(zf.fp)
None

*COMMENT*
As you can see, unlike tarfile zipfile cannot handle a passed path.

--
 3. Zipfile and Tarfile obj API differences.
--

zf.namelist() - tf.getnames()
zf.getinfo(name) - tf.getmenber(name)
zf.infolist() - tf.getmembers()
zf.printdir() - tf.list()

*COMMENT*
Would it have been too difficult to make these names match? Really?

--
 4. Zipfile and Tarfile infoobj API differences.
--

zInfo.filename - tInfo.name
zInfo.file_size - tInfo.size
zInfo.date_time - tInfo.mtime

*COMMENT*
Note the inconsistencies in naming conventions of the zipinfo methods.

*COMMENT*
Not only is modified time named different between zipinfo and tarinfo,
they even return completely different values of time.

--
 Conclusion:
--
It is very obvious that these modules need some consistency between
not only themselves but also collectively. People, when emulating a
file type always be sure to emulate the built-in python file type as
closely as possible.

PS: I will be posting more warts very soon. This stdlib is a gawd
awful mess!
-- 
http://mail.python.org/mailman/listinfo/python-list


[PyWart 1001] Inconsistencies between zipfile and tarfile APIs

2011-07-21 Thread rantingrick

I may have found the mother of all inconsitency warts when comparing
the zipfile and tarfile modules. Not only are the API's different, but
the entry and exits are differnet AND zipfile/tarfile do not behave
like proper file objects should.

 import zipfile, tarfile
 import os
 os.path.exists('C:\\zip.zip')
True
 os.path.exists('C:\\tar.tar')
True
 tarfile.is_tarfile('C:\\tar.tar')
True
 zipfile.is_zipfile('C:\\zip.zip')
True
 ZIP_PATH = 'C:\\zip.zip'
 TAR_PATH = 'C:\\tar.tar'

--
1. Zipfile and tarfile entry exit.
--
 zf = zipfile.open(ZIP_PATH)

Traceback (most recent call last):
  File pyshell#12, line 1, in module
zf = zipfile.open(ZIP_PATH)
AttributeError: 'module' object has no attribute 'open'
 tf = tarfile.open(TAR_PATH)
 tf
tarfile.TarFile object at 0x02B3B850
 tf.close()
 tf
tarfile.TarFile object at 0x02B3B850

*COMMENT*
As you can see, the tarfile modules exports an open function and
zipfile does not. Actually i would prefer that neither export an open
function and instead only expose a class for instantion.

*COMMENT*
Since a zipfile object is a file object then asking for the tf object
after the object after the file is closed should show a proper
message!

 tf = tarfile.TarFile(TAR_PATH)
Traceback (most recent call last):
  File pyshell#72, line 1, in module
tf = tarfile.TarFile(TAR_PATH)
  File C:\Python27\lib\tarfile.py, line 1572, in __init__
self.firstmember = self.next()
  File C:\Python27\lib\tarfile.py, line 2335, in next
raise ReadError(str(e))
ReadError: invalid header
 tf = tarfile.TarFile.open(TAR_PATH)
 tf
tarfile.TarFile object at 0x02C251D0
 tf.fp
Traceback (most recent call last):
  File pyshell#75, line 1, in module
tf.fp
AttributeError: 'TarFile' object has no attribute 'fp'
 tf
tarfile.TarFile object at 0x02C251D0
 tf.close()
 tf
tarfile.TarFile object at 0x02C251D0
 tf.fileobj
bz2.BZ2File object at 0x02C24458
 tf.closed
True

*COMMENT*
Tarfile is missing the attribute fp and instead exposes a boolean
closed. This mismatching API is asinine! Both tarfile and zipfile
should behave EXACTLY like file objects

 f = open('C:\\text.txt', 'r')
 f.read()
''
 f
open file 'C:\text.txt', mode 'r' at 0x02B26F98
 f.close()
 f
closed file 'C:\text.txt', mode 'r' at 0x02B26F98

--
2. Zipfile SPECIFIC entry exit
--
 zf
zipfile.ZipFile instance at 0x02B2C6E8
 zf.fp
 zf = zipfile.ZipFile(ZIP_PATH)
 zf
zipfile.ZipFile instance at 0x02B720A8
 zf.fp
open file 'C:\zip.zip', mode 'rb' at 0x02B26F98
 zf.close()
 zf
zipfile.ZipFile instance at 0x02B720A8
 zf.fp
 print repr(zf.fp)
None

*COMMENT*
As you can see, unlike tarfile zipfile cannot handle a passed path.

--
 3. Zipfile and Tarfile obj API differences.
--

zf.namelist() - tf.getnames()
zf.getinfo(name) - tf.getmenber(name)
zf.infolist() - tf.getmembers()
zf.printdir() - tf.list()

*COMMENT*
Would it have been too difficult to make these names match? Really?

--
 4. Zipfile and Tarfile infoobj API differences.
--

zInfo.filename - tInfo.name
zInfo.file_size - tInfo.size
zInfo.date_time - tInfo.mtime

*COMMENT*
Note the inconsistencies in naming conventions of the zipinfo methods.

*COMMENT*
Not only is modified time named different between zipinfo and tarinfo,
they even return completely different values of time.

--
 Conclusion:
--
It is very obvious that these modules need some consistency between
not only themselves but also collectively. People, when emulating a
file type always be sure to emulate the built-in python file type as
closely as possible.

PS: I will be posting more warts very soon. This stdlib is a gawd
awful mess!
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   8   >