The end to all language wars and the great unity API to come!

2011-07-02 Thread rantingrick
Hello fellow programmers, scripters, hackers, and debutantes.

I have cross posted this thread to three groups that i believe need to
unite under the flag of unity for the benefit of all. Because when we
unite we not only help ourselves, we promote freedom. In the next few
paragraphs i will expose the source of this problem and propose a
viable solution for how WE can solve the problem!

It saddens me when i see API's that don't include at least three
language choices. No *one* language is going to please the masses. I
understand *WHY* this happens however it should never, *EVER* happen
and i cannot lay blame solely on application developers because "we"
have failed to provide them NOT ONLY with a unifying API model, but
also our  respective "plugin" interfaces to that unifying model.

Yes folks  "WE" are to blame for this dilemma. Who is "we" exactly?
"We" is any language community who's language exhibits the traits of
an API scripting language. For me that group includes (at the minimum)
Python, Ruby, Basic, Perl, JavaScript, and whoever else wants to be
part of this group.

Everyone knows that no one language can solve all problems. And
likewise everyone knows that even when two languages are similar (in
few ways, or in many ways) people are always going to draw lines in
the sand and prefer to use one language over another. It is natural to
simply ones working environment. How many of you folks speak English
on Mondays and Mandarin on Tuesdays and Spanish on Wednesdays and
French on Thursdays and Bulgarian on Fridays and Pig Latin on
Saturdays and Orc on Sundays? Anyone? Why i am not surprised!

But we do this very same asinine thing on a daily basis whist jumping
through the productivity limiting hoops. The stench of which rises up
from every community of language developers in the world. We have not
only created a mutual cess pool of laziness and selfishness , we are
wallowing and rooting around in it completely oblivious of our
collectively bombastic stupidity.

So i ask yous, why should we continue to propagate hateful feelings,
or have some among us feel left out because their favorite language is
not included as an alternative in the API they are using at the time?
Why should i need to switch back and forth between multiple languages,
multiple syntaxes, multiple editors, multiple help files, multiple API
help files, and suffer multiple headaches just because the status quo
is to be selfish and not care about the greater "Programming
Community".

"Community". Hmm, now that is a word that can be applied in many
dimensions. The "Python Community" is a community that inherits from
the "Programming Community"... as is the "Ruby Community" and the
"JavaScript Community" and so on and so forth. We are naturally good
at taking care of our immediate community but for the community once
removed we are failing miserably! And this community is the most
important community of all! When we damage the programming community
we damage ourselves and everyone else!

[Thought Exercise] Just imagine for a second if automobiles where
engineered the way programming languages are currently engineered. But
wait! Before we jump into insightful analyolgies we must first
understand why the automobile is such a versatile feat of engineering.
The automobile -- no matter how large or small, not matter if truck or
car or motorcycle or moped-- is designed to interface with a system...
the "highway" system.  The user of an automobile is never restricted
from driving his favorite car. He is always happy because he is free.
Free to choose and free to be HOWEVER NOT THE CASE WITH APIs!

For API's we have just tossed freedom to the wind fro the sake of
selfishness. We would have multiple language developers creating
languages without any regard for a language independent system to plug
said language into. But i am here to tell you that we can be different
with our language style and still promote the freedom to choose. The
tool is NOT Ruby or Python or whatever. The tool is software which
manifests itself as "ones" and "zeros". Layers of abstraction that all
compile to the same base units... 1's and 0's.  Languages are
abstractions of ones and zeros. Languages are NOT tools. Therefore we
all have a vested interest in a unifying API.

Well some would say... " it is up to the developer of an application
what language they choose"... and this is true. But i say they can
choose to allow the users to choose thereby maintaining not only a
happier user base, but a more productive one as well.

When are we going to see the light and start unifying our collective
differences into a singular plug and play API and allowing the user of
"our" abstraction language, "our" for loop, or "our" version of
stdout.write the ultimate of all choices...  the choice of FREEDOM.

for danish inspirations see:

http://wiki.services.openoffice.org/wiki/Uno

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


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread rantingrick
On Jul 2, 6:38 pm, Chris Angelico  wrote:

[... snip expositions...]

> C or C++ bindings will cover most languages.
>
> Chris Angelico

This is pretty much the entire argument, everything else is
exposition.

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


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread rantingrick
On Jul 2, 6:38 pm, Chris Angelico  wrote:
[...]
> It takes work to suit your API to a different language. Let's take GNU
> Aspell as an example; [...] Should the Aspell team offer bindings for every
> known language? In your post, you recommend supporting a minimum of
> three. Which three? Why?

No. Aspell should offer bindings for THE "Unity API" and the
respective "abstraction communities" are then responsible for
maintaining a plugin for their "abstraction" into THE Unity API.

> I'm a great fan of an obscure language named Pike. Do I expect Aspell
> to be available for Pike?

You should expect this. However if it is not available you cannot
blame Aspell for that! No, you MUST blame the pike community.

But first we have to blame EVERYONE because the unity API does not
exist... not yet! Or at least the mindset for it does not exists.

> No, and I wouldn't even if your
> three-language rule were followed.

My rule is for "unlimited unity" not "limited numbers".

> So how can I implement a
> spellchecker in my code? By writing glue. I'll write a module that
> exposes the C++ API to Pike. (This is actually a real example. I ended
> up writing my aspell hook to run as a separate process for isolation's
> sake, but it comes to the same thing.)

Yeah and they have a name for that... "reinventing the wheel". An end
user should NEVER EVER have to write glue code so their "abstraction
of choice" can be used to to script an API. That's like expecting
automobile drivers to build a car from a hunk of iron ore every time!
No, we have car manufactures who specialize in building cars. However
the respective programming language communities are all oblivious to
the greater picture. An iteration is an iteration whether you use the
"for x in iterable: x.blah()" or the "iterable.each{|x| x.blah}" or
WHATEVER syntax you choose to use. It all boils down to the same 1's
and 0's. Can't you see how our own sense of selfish pride is defeating
productivity and discovery? Can't you see?

It's fine to speak French, or Japanese, or English if you want. But
eventually we will need a unifying natural language and likewise a
unifying programming language.

[Note to community] Actually from now on i want everyone to stop using
the words programming and language together. Instead of "X programming
language" i want to you say "X abstraction layer".

Python programming language --> Python abstraction layer.
Ruby programming language --> Ruby abstraction layer.
X programming language --> X abstraction layer.

You see, we constantly refer to languages as tools, and this mindset
is lunacy! All languages compile to 1's and 0's. Languages are not
TOOLS they are all ABSTRACTIONS of a single virtual tool AND THAT TOOL
IS SOFTWARE!). So stop brainwashing yourselves and others with these
foolish descriptors! Begin to focus your mind on unity and
standardization. Then and only then can we combine our singular minds
into the hive mind.


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


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread rantingrick

Take Pidgin[1] as an example. Pidgin is a universal chat client. It's
a glue between the many chat clients that exist... It's a monkey patch
for chat multiplicity but you get the idea. However the Unity API
cannot be a monkey patch. It must be a mutual undertaking from the
beginning. Don't you people understand? Multiplicity is undermining
our future evolution.

[Anecdote]
Once when i was a very young lad (long before computers were
mainstream) i became terribly troubled by the fact that every
generation must spend roughly a quarter of it's lifetime just catching
up to the knowledge of the last generation. This fact does not seem
very troublesome at first glance, but lets create a microcosm...
...what if you suffered from amnesia every
morning and you had to spend 1/4 of the day catching up to where you
were the day before? This would kill your productivity! But that is
not the point i am making here folks! <\back on track> The fact that
we constantly re-invent the wheel is a product of a very important
missing feature of most humans of which is devastating to our
evolution as intelligent agents.

[The Punchline]
Anyway, my solution to this collective "re-education" was the upload.
We could simply plug up, upload all former knowledge, and off we'd
go!

[The Knockout]
However when i shared my solution with someone [unnamed] he laughed
and said: "But that would take the challenge out of life. Nothing
remaining to learn if you can just download it"... aghast with horror
i just shook my head. This person had no imagination!

[The Moral]
Stop being sheep and start the revolution people! Stop being slaves to
multiplicity and be the master of the singularity. Our future (or lack
thereof) is in YOUR hands!

[1] http://www.pidgin.im/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread rantingrick
On Jul 2, 8:12 pm, Chris Angelico  wrote:

> Any universal protocol will suffer either from complexity or
> narrowness - some suffer from both. If every API has to go through
> this Unity API, then either Unity will be as powerful and complex as C
> with all its libraries, or it'll overly restrict things. That's why
> Unity is really just C.

Well i never said we could not just use c of course. I'm trying to
lubricate the imagination here :).

However you have to convince the application devs of that. Most just
create bindings for a well known language like Python or Ruby and call
it a day. However some idiots go as far as writing their own mini
language (Audacity comes to mind!) and we cannot allow this to
happen!

The same problem exists in GUI's. Why the hell is there so many GUI
libraries? How many different label widgets do we need to re-invent?
It's ludicrous! Okay somebody might argue that we cannot just have one
because it would be too large. WHAT! Again imagination is the missing
link here. There is a simple solution... it's called "from GUI import
subset.x.y.z"!

I mean what is the point of having two languages with the exact same
syntax?

Ruby: print 'blah'
Python: print 'blah'

Ruby: for x in blah: blah_blah_blah
Python: for x in blah: blah_blah_blah

WHAT?

This multiplicity reminds me of a beginning CS student code:

def add(1,2):
return 1+2
def add(3,4):
return 3+4
def ...


Instead of:

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

asinine!

Devs preach of code re-use but they propagate multiplicity in their
language design. Sadly we are still in the stone age of programming
and i don't know if i'll live long enough to see a real revolution.
People are waiting in breads lines all day but do not consider why?
(or they are too afraid to ask).

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


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread rantingrick
> On Sat, Jul 2, 2011 at 7:37 PM, Dan Stromberg wrote:
>
> Adding a new API is seldom the way to decrease the number of API's.
> At least, not without -=very=- centralized control over which API's
> get used.
>
> I actually rather like it that no language has achieved the
> dominance today that C once enjoyed, rightly or wrongly.

You make a good point Dan! Like of most of my threads this one is
evolving into something deeper and more profound. Like i recently
pointed out in my last post we have many languages that are just
slightly different (and sometimes spitting images) of others. For
example Python and Ruby share some very close similarities. Of course
they share many differences also but the point is we are duplicating
too much methodology in our language designs.

You make the argument that C is really all you need. And i whole
hearty agree however you must also agree that there is a great need
for Python and Ruby type languages. Languages that are much more user
friendly than C and don't require memory management.

Remember, most API users are not always CS majors. C is not beyond the
scope of any normal functioning human being however it does require
not only a steeper learning curve but caution whilst wielding it. I
mean who wants a seg fault when scripting Open Office, or how about
writing a page of boilerplate for what amounts to a half page script?

For me the ideal situation we could have is a unity of all the high
level languages. Dump all the repeated syntax's and try to compile the
best of all into as few "scripting langages" as possible. Of we can do
it in one GREAT, if not three or so sounds about correct.

Then these "cream of the crop" could be integrated tightly with
extension writing. So that you could start at the scripting level and
move down as needed for speed and low level stuff when needed.

But we need the application devs to take part or the whole house of
cards comes tumbling down. And how do you motivate people to use a
certain API. Simplicity is one way, peer pressure is another, bulling
when necessarily can help. Whatever it takes because we all have a
vested interest in unity. We must start the ball rolling.Continuing to
propagate selfishness is a self defeating process. If you build it
they will come!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread rantingrick
On Jul 2, 8:49 pm, Chris Angelico  wrote:
> On Sun, Jul 3, 2011 at 11:43 AM, rantingrick  wrote:
> > I mean what is the point of having two languages with the exact same
> > syntax?
>
> > Ruby: print 'blah'
> > Python: print 'blah'
>
> > Ruby: for x in blah: blah_blah_blah
> > Python: for x in blah: blah_blah_blah
>
> > WHAT?
>
> What's the point of having fifty languages in which "x+y" is an
> expression whose value is the sum of x and y? Let's ditch 'em all and
> just use one language, since _obviously_ the languages have the exact
> same syntax.

It seem ludicrous at first glance but it is true! We have to much re-
inventing going on!

> Common syntax is an aid to learning. It means you can transfer
> knowledge from one language to another. It doesn't make either
> useless.

Why do you constantly propagate multiplicity? Why do you feel that we
need 100 or so languages when about three would cover everything? Sure
people are free to create whatever Frankenstein language they want in
the confines of their hobby time, but we need standards and we need
them NOW.

We want the world and we want it now!
http://www.youtube.com/watch?v=xkp8fNODegU&feature=player_detailpage#t=472s

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


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread rantingrick
On Jul 2, 10:14 pm, Chris Angelico  wrote:
> I specced up "the perfect language" a while ago. It gave you a clean
> slate with no facilities but one: Define Operator. [...]

That was some great satire :) but the last thing we need is users with
that much power. Take the example of Ruby allowing you to redefine
built in types... disastrous. I understand that freedom is good
however unbridled freedom is a recipe for disaster.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread rantingrick
On Jul 2, 10:57 pm, Gregory Ewing  wrote:
> The place where this "Unity API" idea of yours falls down
> is that an API is only truly easy to use when it's designed
> to closely match the characteristics of the language it's
> being used from.
>
> For example, Python has a very powerful feature that most
> other languages don't have anything remotely like: very
> flexible keyword arguments.

[...]

>
>    win = Window(title = "Fred", width = 300, height = 100,
>      position = (30, 50), movable = True, resizable = True)

With all due respect that's a frail argument Greg. I agree that
python's keyword arguments are great but they can actually cause code
to get messy when so many are passed in a notation like you present
*ahem* ESPECIALLY when "somebody" refuses to follow the style guide
(hint-hint).

I would do this for clarity...

win = Window(
title="Fred",
width=300,
height=100,
position=(30, 50),
movable=True,
resizable=True,
)

psst: removed python style guide abominations :-)
Strangely however it looks very similar to your next notation...

>    win = Window()
>    win.title = "Fred"
>    win.width = 300
>    win.height = 100
>    win.position = (30, 50)
>    win.movable = True
>    win.resizable = True

hmm? I think it's actually easier to read in this final form. However
i will agree that C's requirements for function parameters are a real
pain in the arse. Thank Guido for Python!

> Either way you end up with an API that feels very awkward
> when used from Python.

I think we need to provide a better example (than just mere
conjecture) before we assume how an "imaginary" API would "feel". And
don't forget, any API can feel awkward since you've only got the hooks
that the devs deemed worthy for you to have. I can't tell you how many
obstacles I've had to code around because an API was lacking or buggy.
Turned my otherwise beautiful code into an Orwellian nightmare.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread rantingrick
On Jul 2, 11:00 pm, Gregory Ewing  wrote:
> rantingrick wrote:
> > Ruby: for x in blah: blah_blah_blah
> > Python: for x in blah: blah_blah_blah
>
> Here you're making the mistake of thinking that surface syntax
> is all that matters. Although the 'for' statements in Python and
> Ruby look very similar, underneath they're based on quite
> different mechanisms. They're not equivalent: the Python way
> leads to various powerful things such as generators; the Ruby
> way lends itself more to user-defined control structures.

I agree however i see merit in both approaches. But why must we have
completely different languages just for that those two approaches? We
don't it's just a religious thing.  Doesn't make sense to me. If Guido
and Matz got together over some sake and Monty Python i'll bet they
could hash out a singular replacement fro Ruby and Python in no time!

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


RFC: tkSimpleDialog IMPROVED AGAIN!.

2011-07-03 Thread rantingrick
Hello Folks,

As many of you already know yours truly has posted improvements to the
tkSimpleDialog many moons back HOWEVER i was looking over the code a
few moments ago and realized even more improvements were needed.

These improvements mainly concern naming conventions, comments, and
docstrings although i have some deeper and profound thoughts on
virtual functions/methods that i will probably save for another thread
in the very near future.

As for tkSimpleDialog.py I had to change quite a bit of python style
guide abominations in this and previous edits.

---
First let's see the code in it's ORIGINAL STATE: (Warning: freak show
ahead!)
---

## Start Code: tkSimpleDialog.Dialog ##
from Tkinter import *

class Dialog(Toplevel):

'''Class to open dialogs.

This class is intended as a base class for custom dialogs
'''

def __init__(self, parent, title = None):

'''Initialize a dialog.

Arguments:

parent -- a parent window (the application window)

title -- the dialog title
'''
Toplevel.__init__(self, parent)

# If the master is not viewable, don't
# make the child transient, or else it
# would be opened withdrawn
if parent.winfo_viewable():
self.transient(parent)

if title:
self.title(title)

self.parent = parent

self.result = None

body = Frame(self)
self.initial_focus = self.body(body)
body.pack(padx=5, pady=5)

self.buttonbox()

self.wait_visibility() # window needs to be visible for the
grab
self.grab_set()

if not self.initial_focus:
self.initial_focus = self

self.protocol("WM_DELETE_WINDOW", self.cancel)

if self.parent is not None:
self.geometry("+%d+%d" % (parent.winfo_rootx()+50,
  parent.winfo_rooty()+50))

self.initial_focus.focus_set()

self.wait_window(self)

def destroy(self):
'''Destroy the window'''
self.initial_focus = None
Toplevel.destroy(self)

#
# construction hooks

def body(self, master):
'''create dialog body.

return widget that should have initial focus.
This method should be overridden, and is called
by the __init__ method.
'''
pass

def buttonbox(self):
'''add standard button box.

override if you do not want the standard buttons
'''

box = Frame(self)

w = Button(box, text="OK", width=10, command=self.ok,
default=ACTIVE)
w.pack(side=LEFT, padx=5, pady=5)
w = Button(box, text="Cancel", width=10, command=self.cancel)
w.pack(side=LEFT, padx=5, pady=5)

self.bind("", self.ok)
self.bind("", self.cancel)

box.pack()

#
# standard button semantics

def ok(self, event=None):

if not self.validate():
self.initial_focus.focus_set() # put focus back
return

self.withdraw()
self.update_idletasks()

try:
self.apply()
finally:
self.cancel()

def cancel(self, event=None):

# put focus back to the parent window
if self.parent is not None:
self.parent.focus_set()
self.destroy()

#
# command hooks

def validate(self):
'''validate the data

This method is called automatically to validate the data
before the
dialog is destroyed. By default, it always validates OK.
'''

return 1 # override

def apply(self):
'''process the data

This method is called automatically to process the data,
*after*
the dialog is destroyed. By default, it does nothing.
'''

pass # override
## End Code: tkSimpleDialog.Dialog##

As you can see this code reeks of abominations. Not only is the
interface poorly designed, but we have poor naming conventions, too
much vertical spacing, unhelpful and poorly formatted doc-strings, not
enough comments where needed and too many in other places. Not the
kind of code you bring home for mom to stick on the fridge. D:

---
Now lets see the code in it's CURRENT STATE (with cleaned up comments
and doc-strings!)
---

## Start Code: New and improved dialog! ##
import Tkinter as tk

class Dialog(tk.Toplevel):
def __init__(self, parent, title='Dialog'):
"""
Initialize a dialog;
parent:
A Tkinter.Toplevel instance.
title:
The dialog's title as a string.
"""
tk.Toplevel.__init__(self, parent)
self.withdraw()
if parent.winfo_viewable():
# If the parent window is not viewable, don't
# make the child transient, or else it would be
# opened withdrawn!
self.transi

Implicit initialization is EVIL!

2011-07-03 Thread rantingrick
Tkinter has a major flaw and this flaw has been with us for many many
years. What is the flaw? Well the title says it all folks... IMPLICIT
INITIALIZATION IS EVIL. Still confused, well let me explain.

Unlike most GUI libraries the Tkinter developers thought is would
"just wonderful" if the root GUI window just sprang into existence if
the programmer "somehow" forgot to create one. Does anyone remember
the old adage...

   """ The road to hell is paved with good intentions? """

...as you're about to see this road is paved in gold around thee
parts!  You're probably thinking to yourself that i am stretching the
truth for the sake of drama? Well i wish i could answer yes, but i
cannot. So without further "a due" let me show you some code...

## START CODE ##
from Tkinter import *
label = Label(parent=None, text='This is an example of poor GUI
design!')
label.pack()
label.mainloop()
## END CODE ##

As you can see the root window is auto created for the caller and this
sort of hand holding only served to confuse the hell of out new folks!
Sure it's "cute" (and all that type of nifty swiftly crap!) but it is
EVIL! A new user should learn from day one the hierarchy of a GUI.

-root window
-optional widgets
--optional sub windows
---optional widgets
---and on and on

root = Tk() # Or a derived class of Tk
frame = Frame(root)
w = Widget(frame)
and on and on and on

We should never propagate this sort of confusion throughout our
community. Please remove this dangerous design pattern immediately.
-- 
http://mail.python.org/mailman/listinfo/python-list


Virtual functions are virtually invisible!

2011-07-03 Thread rantingrick

Hello Folks!

In my quest to uncover the many asininities contained within the
tkSimpleDialog.py module i found myself contemplating some the very
fundamental aspects of the Python language proper. And this is aspect
be... "Pythonic notation".

But before i introduce you to my latest discovery of collective
ineptitude i want to discuss some of the great pythonic notations we
already enjoy.

In the beginning, Mr. Van Rossum (in a stroke of complete brilliance i
might add!) stumbled upon the idea of syntactical notation and he
seized upon it! We all know how python uses indention to denote scopes
(and i just love this aspect about the language!) but my next favorite
notation is the leading and trailing double underscores that wrap
special method names[1] Because they just JUMP out at you whilst
reading code (and they should!). Even if they only say...

 """Hey, i am special and you should only care about me if you are an
experienced pythonista, otherwise nothing to see here, move along
lad!"""

Actually i did not realize just HOW important this notation was to my
code comprehension until i started tinkering with another language
called "Ruby" (who BTW does not use any notation for this matter).
Ruby doesn't use any special notation so all the member methods just
blend into the crowd.

Nothing jumps out and says "HEY, I'M SPECIAL, LOOK AT ME"... instead
you start to get sea sick from the homogeneous structure of it all.
You cannot quickly categorize the method hierarchy without extensive
reading and wasted time. This is a shame!

But this gushing over underscores is not the subject of my thread
today, what concerns me is the fact that virtual methods in derived
classes just blend in to the crowd. For me this presents major
problem, because i don't know what "behind the scenes" actions are
going to take place without a very personal relationship with the
underlying code base. More wasted time!

So what i am proposing is some way to differentiate methods that have
been clobbered by the derived class. And it's not the fact that they
have been clobbered that is of any concern to me, NO, what concerns me
is that i don't know what "invisible" side effects are taking place
"behind-the-scenes",  much less which methods are the root of such
invisible side effects.

You know as Pyhthonista's we always frown on syntactic decorators
HOWEVER like all good things these visual cues are best taken when in
moderation. I believe in these cases syntactic decorators are not only
needed but they are warranted!

Of course the simplest solution is a doc string explaining the case to
a reader. But as we all know even pyhtonista's refuse to follow the
style guide so this will be a non starter. I think we really need some
sort of visual cue in the form of forced syntactical notation (just
like the special method underscores).

[1] http://docs.python.org/reference/datamodel.html#special-method-names
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RFC: tkSimpleDialog IMPROVED AGAIN!.

2011-07-03 Thread rantingrick
Sorry folks. I found a few bugs in that pasted code of the new and
improved tkSimpleDialog. I believe most here could debug it however
just in case any newbies are watching i want the code to execute
without error.


## START CODE ##
import Tkinter as tk

MESSAGE = """
You are following bad design patterns.
NO SOUP FOR YOU!
"""

class Dialog(tk.Toplevel):
def __init__(self, parent, title='Dialog'):
if not isinstance(parent, (tk.Tk, tk.Toplevel)):
raise Exception(MESSAGE)
"""
Initialize a dialog;
parent:
A Tkinter.Toplevel instance.
title:
The dialog's title as a string.
"""
tk.Toplevel.__init__(self, parent)
self.withdraw()
if parent.winfo_viewable():
# If the parent window is not viewable, don't
# make the child transient, or else it would be
# opened withdrawn!
self.transient(parent)
if title:
self.title(title)
self.parent = parent
# self.result is where we store any values for return to
# the caller.
self.result = None
# We save the dialog's main widget frame just incase a
# caller needs to access it later.
self.frame = tk.Frame(self)
# Next we call self.body to create the body of the dialog.
# We save the return value as "self.initial_focus" so we
# give it focus later.
self.initial_focus = self.body(self.frame)
self.frame.pack(padx=5, pady=5)
self.buttonbox()

def show(self):
# XXX: Need "show" and "show_modal" methods!
self.deiconify()
# The window needs to be visible for the grab so we
# call wait_visibility and let Tkinter do the waiting
# for us.
self.wait_visibility()
self.grab_set()
if not self.initial_focus:
self.initial_focus = self
self.protocol("WM_DELETE_WINDOW", self.cancel)
if self.parent is not None:
self.geometry(
"+%d+%d" %(
self.parent.winfo_rootx()+50,
self.parent.winfo_rooty()+50)
)
self.initial_focus.focus_set()
self.wait_window(self)
return self.result

def destroy(self):
"""Destroy the window."""
self.initial_focus = None
tk.Toplevel.destroy(self)
#
# Construction Hooks.
#

def body(self, master):
# XXX: create_body
"""
OVERIDE: Create dialog body and return widget that
should have initial focus.
"""
pass

def buttonbox(self):
# XXX: create_buttonbox
# XXX: Overiding this method can break funcionality if
#  you do not properly bind the ok and cancel buttons
#  correctly!
# RFC: Should we create a generic button creation method
#  or a mixin?
"""
Add a standard button box;
Override if you do not want differnt buttons.
"""
box = tk.Frame(self)
w = tk.Button(
box,
text="OK",
width=10,
command=self.ok,
default=tk.ACTIVE
)
w.pack(side=tk.LEFT, padx=5, pady=5)
w = tk.Button(
box,
text="Cancel",
width=10,
command=self.cancel
)
w.pack(side=tk.LEFT, padx=5, pady=5)
self.bind("", self.ok)
self.bind("", self.cancel)
box.pack()

#
# Standard Button Callbacks.
#

def ok(self, event=None):
# XXX: okButtonCallback | callbackOkButton | (cb*|*cb)
""" Proces the data automatically when user presses ok
button."""
if not self.validate():
self.initial_focus.focus_set() # put focus back
return
self.withdraw()
self.update_idletasks()
try:
self.apply()
finally:
self.cancel()

def cancel(self, event=None):
# XXX: cancelButtonCallback | callbackCancelButton | (cb*|*cb)
""" Return focus to the parent window and destroy self"""
if self.parent is not None:
self.parent.focus_set()
self.destroy()

#
# Command Hooks.
#

def validate(self): # XXX: data_validate
"""
Validate the data;
This method is called automatically to validate the data
before the dialog is destroyed. By default, it always
validates
True. Overide to change behavoir to something more suitabe for
your derived dialog.
"""
return True

def apply(self): # XXX: data_process
"""
Process the data;
This method is called automatically to process the data
but only *after* the dialog is destroyed. By default, it does
nothing. Overide to change the behavoir to something more
suitabe
for you

Re: Problem!!

2011-07-03 Thread rantingrick
On Jul 3, 6:41 pm, amir chaouki  wrote:
> i have written code on linux for parsing text files and it works great
> but when i try to run it on windows it goes crazy, do you have any
> idea???

psst: you should show us the code first. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit initialization is EVIL!

2011-07-04 Thread rantingrick
On Jul 4, 3:33 am, Gregory Ewing  wrote:

> IMO the real problem here is the existence of a privileged
> "root" window at all. No GUI platform I know of has any
> such concept (except for a "desktop" window that represents
> the whole screen, which is not the same thing). All top-level
> windows should have equal status.


I dunno, it's natural to create a parent-child hierarchy when GUI
programming with any library. So i am not completely sure what you are
implying here? When you close the main application widow you would
expect all child windows to close. Or likewise when you iconify the
main window you would expect the other windows to do the same. Sure
you could do this yourself by sending messages to all the other
windows but Tkinter does this for you automatically. And how does
Tkinter know which windows to configure? A parent-child relationship
that's how.

>>> a = set(dir(Tkinter.Toplevel))
>>> b = set(dir(Tkinter.Tk))
>>> len(a), len(b)
(222, 226)
>>> a.difference(b)
set(['_setup', '_do'])

You say "root" windows are bad however any parent-child relationship
has to BEGIN somewhere. For Tkinter the beginning of this dynasty is
an instance of the Tkinter.Tk[1] window from which all other windows
and widgets are made children. HOWEVER any of the windows ARE in fact
instances of Tk.Toplevel[1]. So they ARE all equal because they all
have the same methods available to them.

>>> import Tkinter
>>> Tkinter.Tk.__doc__
'Toplevel widget of Tk which represents mostly the main window\nof
an appliation. It has an associated Tcl interpreter.'
>>> import inspect
>>> inspect.getmro(Tkinter.Tk)
(, ,
)
>>> inspect.getmro(Tkinter.Toplevel)
(, , , )

But let's dig a little deeper here. Your comment suggests that you
"personally" need to create multiple windows for your applications. Is
this correct? If so i pity any users of such application as they would
be thoroughly confused. Most applications consist of one main window
(a Tkinter.Tk instance). The only need for extra Toplevel windows is
in the form of modal dialogs (use tkSimpleDialog.Dialog) or tool
windows (use Tk.Toplevel with attribute '-toolwindow'=True).

I don't see how your statements carry any weight here. Could you
explain please?

[1] http://effbot.org/tkinterbook/tkinter-application-windows.htm
[2] http://effbot.org/tkinterbook/toplevel.htm
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit initialization is EVIL!

2011-07-04 Thread rantingrick
On Jul 4, 3:44 am, Chris Angelico  wrote:

> I don't know Tkinter, but from the look of the example code, he's
> creating a Label that's not attached to a window, and then packing it
> into nothing. The toolkit kindly creates him a window. Is that the
> "root GUI window" that he means? A basic top-level window?

Yes. But to be specific the "root" is an instance of Tkinter.Tk which
is a toplevel that has a TCL interpreter attached.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit initialization is EVIL!

2011-07-04 Thread rantingrick
On Jul 4, 10:40 am, Chris Angelico  wrote:

> Uhh, sorry. No. There are plenty of good reasons for one application
> to make multiple top-level windows, and if I ever find myself using a
> toolkit that makes this difficult, I'll either be hacking the toolkit
> or using a different one. I've been building GUI applications for far
> too long to not want features like that.

And those reasons are...?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit initialization is EVIL!

2011-07-04 Thread rantingrick
oops. should have used symmetric_difference!

>>> a.symmetric_difference(b)
set(['_w', '_setup', 'report_callback_exception', '_do',
'__getattr__', 'loadtk', '_loadtk', 'readprofile'])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The end to all language wars and the great unity API to come!

2011-07-04 Thread rantingrick
On Jul 4, 12:06 am, alex23  wrote:
> rantingrick  wrote:
> > But why must we have
> > completely different languages just for that those two approaches?
>
> Because monocultures die.

That's an interesting statement Alex (even though you parrot it
constantly). So what IS a mono culture exactly? Lemme see...

   """A single, homogeneous culture without diversity or dissension.
"""

Interesting. Would you consider the Python community to be a
monoculture? We are working towards a singular goal so i would say so.
We should be working towards the language that is best for all but
instead we are working towards the language that is best for US.

How about the Ruby community?

Here's a good one; How about the programming community? These groups
would ALL classify as monocultures Alex. So why are they NOT dying?
Well maybe they are and you just cannot see past your own nose (it
does get fairly long from time to time you know).

I believe (unlike most people) that nature is striving for perfection
NOT for diversity. Diversity is just a byproduct of feeble attempts to
GUESS the correct answer. Here is a thought exercise for the advanced
reader...Which is more efficient; Numerous groups working to create
languages that satisfy their selfish needs OR one group of all the
bright minds working to destroy multiplicity and bring about the one
true language that meets the needs of productivity?

In order to achieve perfection we must propagate unity within the
system and we must destroy multiplicity with a vengeance. We must
unite to defeat multiplicity and in doing so we create innovation.
That is the job of intelligent agents, to BRING ORDER TO THE NATURAL
CHAOS OF THIS UNIVERSE! Your natural instincts are of propagating
diversity (read as selfishness) HOWEVER the future exists only in
unity.

What do you think will be the eventual outcome of the human existence
Alex? Since you have no imagination i will tell you, a singular
intelligence. However an intelligence that is the product of many
"intelligent agents". A unity intelligence if you will. Just think of
it as a botnet alex, i am sure you have plenty of experience in this
area!

> Because having broader diversity leads to more evolutionary leaps.

Do you think that if we combine all the worthwhile attributes of the
high level languages that somehow everyone is just going to accept
that forever? No, of course not. HOWEVER instead of splitting off into
sects (and damaging our hive mind capabilities) we need to focus our
efforts on one goal... CREATING THE BEST LANGUAGE WE CAN AT ANY ONE
TIME IN HISTORY... and we will all learn TOGETHER not APART. Diversity
only propagates multiplicity and slows our evolution Alex. It is
selflessness on a grand scale.

> Because the implementations are so fundamentally different.

In the big picture that's untrue. Between say Ruby and Python you a
few LARGE differences and many SMALL differences (and even some
replication). I propose that we combine the Ruby and Python languages
using all the best ideas, however dropping the multiplicity.

> Because the people who ACTUALLY WROTE THE LANGUAGES wanted to explore
> different implementations.

Why can they not explore within the hive mind? Why must they hide
their explorations from the greater group. SELFISHNESS

Here is another thought exercise for the advanced reader. Remember in
the old days when furniture was crafted by hand? Not only was the
furniture EXPENSIVE it was also scarce to come by. Why was this the
case. Because human nature is to be selfish. And our selfishness slows
evolution. But one day some very intelligent chap realized that he
could build furniture not only faster but cheaper by using the
assembly line. Now we have furniture stores on practically every
corner at prices almost anyone can afford. Yes i realize "some" of the
products are not of good quality but that is a result of economics
(and greed) not unity.

> Because the people who ACTUALLY WROTE THE LANGUAGES wanted to explore
> different syntax & semantics.

We should have nailed down syntax and semantics long ago alex! This
should have been step one. No instead we have groupA, groupB, and
groupC still fighting about what is best for their selfish needs
without concerning themselves wit the big picture. It's not what is
best for ME, NO, it's what is best for US.

 * What syntax is most widely intuitive?
 * What semantics are the best for productivity?
 * etc...

> Because learning different approaches expands your appreciation of &
> informs your understanding of both.

Yes, and i agree. But instead of learning in small groups we need to
learn together. Of course we are going to make mistakes along the way.
Heck we may even have to re write the whole spec a time or two. But i
would argue that the chances of making mistakes decrease as the number
of agents increase. I dunno, have

Re: Implicit initialization is EVIL!

2011-07-04 Thread rantingrick
On Jul 4, 11:01 am, Chris Angelico  wrote:
> On Tue, Jul 5, 2011 at 1:46 AM, rantingrick  wrote:
> > On Jul 4, 10:40 am, Chris Angelico  wrote:
>
> >> Uhh, sorry. No. There are plenty of good reasons for one application
> >> to make multiple top-level windows, and if I ever find myself using a
> >> toolkit that makes this difficult, I'll either be hacking the toolkit
> >> or using a different one. I've been building GUI applications for far
> >> too long to not want features like that.
>
> > And those reasons are...?
>
> As varied as the applications that call on them. One example that
> springs to mind: Our database front end has "table view" and "record
> view", where you get one table view and from that you can view as many
> records as you like. Users may choose to effectively switch from one
> view to the other, or they may open up two or more record views and
> have them and the table view all on screen simultaneously.

> This is not
> a modal dialog; it's not even a modeless dialog - it's a completely
> stand-alone window that can be moved around the Z order independently
> of the parent.

You can do the exact same thing with Tkinter's windows.

> There's a definite ownership based on process, though;
> terminate the process (by closing the table view) and it must close
> all record views first. I've done other applications where this has
> not been the case - where all top-level windows are truly equal - but
> not in this instance.

Tkinters Toplevels ARE equal!

However in this case you should spawn a new instance of the
application "opened" at that particular table view. It's as simple as
a few command line arguments in your script.

It's like a text editor, you never want a "New" command that resets
the current document or an open command that resets the current
document and loads the file into the existing editor. Each application
instance should only create one document and stick with it until it is
closed.

Instead you want to spawn a new instance of the editor and tell the
editor (via command line arguments) to load file data (if applicable).
Simple command line arguments (of which you should be using anyway)
are the key here. All part of proper software design.

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


Re: Implicit initialization is EVIL!

2011-07-04 Thread rantingrick
On Jul 4, 12:41 pm, Chris Angelico  wrote:

> For another example, look at where web browsers are going. By your
> description, one instance of a browser should work with precisely one
> "document" (which in this case would be a web page). That's how
> browsers were in the early days, but by the early 2000s most browsers
> had some form of tabs, letting you keep that application in one
> window.

Umm, if you want to see where things are "going" you should learn
about the inner workings of chrome which actually spawns a new process
for every tab created; which has the benefit of avoiding application
lock up when one page decides to crash.

> I currently have precisely two slots in mindspace for web browsers:
> Chrome and Firefox. Chrome currently has about a dozen tabs up;
> Firefox about the same, but most of them are long-term status reports
> that I keep handy. If I had to have 20-30 separate windows, I would
> not be able to use alt-tab to find the one I want, but would have to
> use some other kind of "window picker". How would you write a
> user-friendly picker that can cope with myriad instances of
> everything?

psst: it's called a notebook in GUI jargon. Again, study up on chrome
internals.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Testing if a global is defined in a module

2011-07-04 Thread rantingrick
On Jul 4, 1:11 pm, Tim Johnson  wrote:
> Using Python 2.6 on ubuntu 10.04.
> inspect module :
> I want to 'inspect' a module and get a list of all
> functions, classes and global variables in that module.
>
> ## A module has been imported, and we call `getmembers'
> members = inspect.getmembers(mod)
>
> ## While iterating thru `members', we test to see
> ## if an object is defined in the module.
> for m in members:
>   obj = m[1]
>   res = inspect.getmodule(obj)
> ## It appears that getmodule returns None for
> ## all but functions and classes.
>
> Example, for a module name `mvcInstall', when a class
> name `Install' that is defined in the module
> is passed as an argument to inspect.getmodule, the
> values returned is something like
> " '/home/tim/prj/cgi/libraries/python/mvcInstall.py'>"
> Likewise for functions defined in the module.
>
> ** But ** when global variables such as strings, booleans,
> integers are passed as an argument to getmodule, the
> value returned is `None'.
>
> What else can I do here?
> thanks
> --
> Tim
> tim at johnsons-web dot com or akwebsoft dot comhttp://www.akwebsoft.com

Well if you follow the python style guide (and most accepted styles
for global notation) then it's a trial exercise. You don't even have
to import anything!!! :)

>>> GLOBAL_STR = 'str'
>>> GLOBAL_FLOAT = 1.3
>>> GLoBaL_Bs = ''
>>> dir()
['GLOBAL_FLOAT', 'GLOBAL_STR', 'GLoBaL_Bs', '__builtins__', '__doc__',
'__name__', '__package__', 'item']
>>> for item in dir():
if item.isupper():
print 'Found Global!', item


Found Global! GLOBAL_FLOAT
Found Global! GLOBAL_STR

;-)

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


Re: Testing if a global is defined in a module

2011-07-04 Thread rantingrick
On Jul 4, 3:30 pm, Tim Johnson  wrote:
>
>   Thanks for the reply: *but*
>   dir() will also show globals from other modules imported
>   by the target module. So I would need a way to distinguish between
>   those imported and those defined in 

Okay, then do some processing on the source. You can use regexps or
the module mentioned earlier by Chris.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The end to all language wars and the great unity API to come!

2011-07-05 Thread rantingrick
On Jul 4, 2:36 am, Gregory Ewing  wrote:

> We have different languages because different people have different
> ideas about what a language should be like. Ruby people like user
> defined control structures; Python people regard user defined
> control structures as an anti-feature. It's fundamentally
> impossible for one language to satisfy both sets of people.

I was thinking more about this comment and it occurred to me that
Python does have user controlled data structures. Just because there
is no "top level syntax" like ruby does not mean these do not exists.
You only have to look below the surface. Take the sort methods of
lists for example...

>>> lst = [
(100, 0),
(25, 2),
(10,1),
]
>>> lst
[(100, 0), (25, 2), (10, 1)]
>>> lst.sort()
>>> lst
[(10, 1), (25, 2), (100, 0)]
>>> lst.sort(lambda x,y: cmp(x[1], y[1]))
>>> lst
[(100, 0), (10, 1), (25, 2)]

...that looks like a "user defined control" structure to me. So how
can an anti-feature become part of the language proper? (devils
advocate here) :)

I leave the discovery of other user defined control structures for the
advanced readers.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The end to all language wars and the great unity API to come!

2011-07-05 Thread rantingrick
On Jul 5, 11:04 am, Corey Richardson  wrote:

> How is giving the sort method a function by which to determine the relative
> value of objects a control structure? Do you know what a control structure is?
> It's something that you use to modify control flow:
>
> if foo <= bar:
>         foo += 1
> else:
>         bar += 1

Interesting, corey. Very interesting. However the fun is yet to come
so stay tuned...

> That's a control structurem the "if-else". I don't know what Ruby calls a
> control structure, but that's what it is. for and while are in there too.
> When you run lst.sort(lambda x, y: cmp(x[1], y[1])), what happens?

So are you suggesting that a control structure must have at minimum
one of "for", "while", or "if"? Okay, i listening. Go on...

> We'll call that argument srt, here's a sample (naive) implementation:
>
> def sort(key):
>         lst = self.internal_list
>         for n in range(len(self.internal_list) - 1):
>                 for i in range(len(self.internal_list) - 1):
>                         if srt(lst[i], lst[i+1]) < 0:
>                                 lst[i], lst[i+1] = lst[i+1], lst[i]
>
> See what's in there? An if.

Yes there IS and "if" in there and IF you look closely enough you may
see two "for"'s also. So by your own definition this (naive) code
qualifies as a control structure. Interesting Corey, very
interesting.

But wait just a second Corey. My statement has nothing to do with
sort. sort is just the vehicle. My statement is that the cmp argument
to sort IS a user defined control structure (the code block to be
exact). It doesn't matter that the code is contained in a function
object. That's like saying a cake is not a cake because it was
packaged in a shoe box instead of a cake box.

> Sure, WHAT the if does is user-controlled with the
> key,

Well as long as you can admit that fact.

> but that doesn't make that particular if a new control structure,

Oh i see. Change the rules as we go eh?

> and
> it certainly doesn't make the key a control structure. You can pass a key
> to a sort even in C and that certainly doesn't have user defined control
> structures.

What the hell does C have to do with Python Corey? One thing is for
sure, i always get a giggle from your self defeating posts. You're the
best enemy a person could have. Thank you. *bows*

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


Re: Implicit initialization is EVIL!

2011-07-05 Thread rantingrick
On Jul 5, 10:17 am, Chris Angelico  wrote:

> It's actually quite easy to implement this, even if you _are_ forced
> to have one primary window. You just have an invisible primary whose
> sole purpose is to "be the application", and then everything else is
> secondary windows. Kinda defeats the purpose of forcing applications
> to have one primary window, though.
>
> To my thinking, there will always be one primary *thread*, and GUI
> facilities are secondary to the process, never the other way around.
> When the main thread exits, the process ends.


Chris are you playing devils advocate (for my team). I am confused? :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit initialization is EVIL!

2011-07-05 Thread rantingrick
On Jul 5, 11:00 am, Web Dreamer  wrote:

> What he means is that On Mac, if you close "all" windows, the application is
> still running.

Then that is NOT closing windows that is only ICONIFIYING/HIDING them.
Let's use the correct lingo people!

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


Re: Implicit initialization is EVIL!

2011-07-05 Thread rantingrick
On Jul 5, 6:14 am, Gregory Ewing  wrote:
> rantingrick wrote:
> > Most applications consist of one main window
> > (a Tkinter.Tk instance).
>
> You've obviously never used a Macintosh. On the Mac, it's
> perfectly normal for an application to open multiple
> documents, each in its own window, with no one window
> being the "main" window. Any of them can be closed (or
> even *all* of them) and the application continues to run
> until you explicitly quit it.

And how do you EXPLICITY quit the application? Because the interface
for window management(on windows box) is three buttons "minimize",
"maximize", and "destroy". If closing the window only "hides" the
window then you are just "managing" a window's "visibility". We are
talking about destroying GUI processes here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit initialization is EVIL!

2011-07-05 Thread rantingrick
On Jul 5, 6:20 pm, Chris Angelico  wrote:
> On Wed, Jul 6, 2011 at 8:42 AM, rantingrick  wrote:
> [...]
> > On Jul 5, 11:00 am, Web Dreamer  wrote:
> >> What he means is that On Mac, if you close "all" windows, the application 
> >> is
> >> still running.
>
> > Then that is NOT closing windows that is only ICONIFIYING/HIDING them.
> > Let's use the correct lingo people!
>
> Actually, it IS closing those windows. Why wouldn't it be?
> [...]
> The memory used by that window can be reclaimed. Handles to its
> objects are no longer valid. The window really is closed. The
> application might not have terminated, but that window has not been
> minimized - the *window* is closed.

And you need the OS to that for you!?!? Are you joking?

> I could conceivably write a program that sits invisibly in the
> background until a network message arrives. Upon receipt of such a
> message, the program initializes the GUI subsystem and opens a window.
> When the user closes the window, the program flushes all GUI code out
> of memory and waits for the next message. While it's waiting, is there
> any "main window" that exists but has just been hidden? No. But is the
> application still running? Of course! Completely separate.

And so could i using Tkinter and it's "supposedly" flawed window
hierarchy. Remind me again why we are discussing this?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit initialization is EVIL!

2011-07-05 Thread rantingrick
On Jul 5, 6:54 pm, Chris Angelico  wrote:

> To do what for me? Close windows? Reclaim memory? Terminate
> applications? I don't understand your bogglement.

ClaimA: I made claim that Tkinter's window hierarchy is not only
normal, but justified in modern GUI programming.

ClaimB: You made a claim ( or supported a rebuttal claim) that Mac's
system of window management was superior and did not need such a
"window hierarchy" simply because;

1. You can create a program that twiddles it's thumbs (using very
little memory) until a message is received.
2. Upon receiving a message the program can open a GUI window.
3. When the user closes the GUI window (definition of "close" is not
nailed down yet!) the program will free the GUI memory and start
twiddling it's thumbs again until the next message arrives.
4. rinse and repeat until you are happy.

It's obvious that yours and my claims are contradicting. So with that
said, at what point does Tkinter or Windows fail in this example you
provide? Because, i can recreate the exact same functionality on a
windows box without need of the underlying window manager's help.

1. What is your point?
2. And how does it prove my position incorrect?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit initialization is EVIL!

2011-07-05 Thread rantingrick
On Jul 5, 7:34 pm, Chris Angelico  wrote:

> Actually, everything you do requires the underlying window manager,
> otherwise you're just painting your own pixels on the screen. And I
> never said that this model was possible in some and not others.
> (Although it's a bit harder with Windows; there's no explicit call to
> finalize windowing, so most likely the application will hold GUI
> memory until termination.)

Ah ha. I think we are getting somewhere now. Everything up to this
point has been mostly exposition :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The end to all language wars and the great unity API to come!

2011-07-05 Thread rantingrick
On Jul 4, 6:24 pm, Steven D'Aprano  wrote:
> rantingrick wrote:

> Some people want to make Python more dynamic. Some want it to be less
> dynamic. Some care about integrating it with Java or .Net, some don't care
> about either. Some are interested in clever optimization tricks, some
> oppose adding any more complexity.
>
> Some want it to be faster, and are happy to throw more memory at it to do
> so. Some want it to use less memory, because on embedded devices and smart
> phones memory is the bottleneck, not time.
>
> Some only program in Python. Some treat Python as merely one language out of
> many that they use.
>
> Some come to Python from the C/C++ community, and their wants are influenced
> by C. Some come to Python from Lisp, Scheme or Haskell, and their wants are
> influenced by functional programming ideas. Some have never programmed
> before, and don't know want they want.

And are any of them getting what they want? No. And they should not.
(stay tuned for the reason "why not")

> Define "best for all", and try not to make it "what Rick wants".

You want features? And remember i am talking about scripting/glue
level languages here. Something to replace Python, Ruby, Perl,
JavaScript, etc, etc not some "pie-in-the-sky",  "single-answer-to-all-
our-problems" pipe dream language.

 * Intuitive syntax.
 * Productivity friendly.
 * Complex enough to solve large problems but simple enough for simple
problems (that does include extending into C when needed)
 * Multi paradigm (problem
 * Promotes a culture of code readability (because people read source;
not just machines!).
 * there is always more.
 * we all know this list steven!

> No, Python is not a monoculture. There are the Stackless, Jython, PyPy and
> IronPython sub-cultures, all with their own needs, wants and desires. There
> are sub-cultures for embedded devices and smart phones, sub-cultures for
> those who use Python as a teaching language, for web development, for GUI
> development, and for system administration. There are the Numpy and Scipy
> sub-cultures, sub-cultures in the fields of linguistics and biology.

Hmm. Just think how far ahead we would be if these folks would stop
trying to support petty differences and focus on a singular Python
language?

But let's not kid ourselves here!

This problem is far bigger than python. Selfishness infests every
group of humans on this planet. Why do we need multiple OS's? Just so
one can say "\" is the proper file path sep and someone else can say
"/" is the proper one! Are you kidding me?

Look at the multiplicity. Look at the asinine nature of it all and for
once in your life join the group that is the future of human
evolution, not the evolutionary dead-end! BTW: Tell Lucy i said hello!


> Nature isn't striving for anything.
> [...]
> what you believe is not new and it is
> not a minority view. It is old, obsolete,

Before you go out babbling about "concepts" you should understand what
these "concepts" are; or at least at the minimum read the freaking
Wiki! My statements are in no way remotely related to "Great Chain of
Being" and this feeble attempt to prove so is obviously another one of
your half stuffed straw-men arguments.

> and the vast majority of people
> with no modern biology education believe something like it.

You sure presume to know quite a lot about "uneducated people". Do you
know these folks personally? Do you chit-chat with them on the subway
or whilst sharing a Frappuccino?

> Since needs are frequently in opposition (e.g. the speed/memory trade-off),
> a single "true language" must be a compromise language that leaves nobody
> happy.

Oh Steven, that's just your fear of unity acting out again. Yes,
what's good for the group will not *always* be good for you, or me, or
xah lee! But what matters is progress. Not your selfish needs Steven.

> Or some dictator (Rick?) declares that such-and-such a set of
> features is, by definition, the "perfect" language and those who want
> something else have to miss out.

I have never held myself out as some sort of dictator. These decisions
must be made in a democratic manner. This is FUD.

> Imagine a world where *every* shop was Walmart. That would be good for
> Walmart, but terrible for everyone else. That's Rick's plan for
> programming.

You know Steven, wal-mart is a very successful company. And wal-mart
meets the needs of the many. Again you fail to see the truth behind
the curtain. If (as you say) wal-mart really is such a bad company and
it's existence is hurting "the many"... then explain to the class (if
you can) why wal mart is the most successful retail chain in the
history of the world?

We are listening...

Re: Implicit initialization is EXCELLENT

2011-07-05 Thread rantingrick
On Jul 5, 10:26 am, Steven D'Aprano  wrote:
> This is not strictly Python, although it is peripherally relevant.
>
> Some month or three ago, I read an article or blog post about API design,
> specifically the wrong-headedness of insisting that callers manually
> initialise instances using a separate step after creation.
>
> The argument goes, if your API looks something like this:
>
> instance = Spaminator(extra_truffles=False)
> instance.activate()
> instance.nom_nom_nom()
> => prints "yummy spam, the food of the Gods!!!"
>
> chances are that you are doing it wrong and your users will hate you. Why
> force the user to manually "flip the switch" (so to speak)? It's not like
> they can possibly avoid it:

I completely agree!

> Exceptions to this rule are if the Spaminator has side-effects (e.g. files,
> in which case the user may want finer control in when they are opened and
> closed), or if there are meaningful operations you can perform on an
> inactive Spaminator.

Agreed again!

> It's also relevant to
> tkinter, which will implicitly create a root window for you when needed.

WRONG.
Oh wait,
of course,
you are correct!
YES!
Maybe we should have library modules import only when needed! i mean,
who needs those pesky import statements anyways! Sure it will slow
down run time BUT WHO CARES! My gawd, you just opened my mind to so
many possibilities! Why stop at library modules, if it is not there
just download the source at run time! Guido really dropped the ball on
this one folks.

> Since you can't do anything without a root window, I don't see the benefit
> in forcing the user to do so.

The reason is simple. It's called order. It's called learning from day
one how the order of things exists. Widgets are part of windows, not
the other way around. Saving a few keystrokes is not acceptable if you
jumble the understanding of a new student. To understand and use
Tkinter properly you must understand the order of window->widget.

> When they need to learn about root windows,
> they will in their own good time.

So you would start drivers education class with road construction? Or
the history of the internal combustion engine? Who cares about
actually *driving* the car.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit initialization is EXCELLENT

2011-07-05 Thread rantingrick
On Jul 5, 9:44 pm, Chris Angelico  wrote:
> On Wed, Jul 6, 2011 at 11:53 AM, rantingrick  wrote:
> > So you would start drivers education class with road construction? Or
> > the history of the internal combustion engine? Who cares about
> > actually *driving* the car.
>
> I believe that starting driver ed with some basics of how an internal
> combustion engine works would be a Good Thing. If you're going to be
> in control of a ton of steel that's capable of moving at a hundred
> kays, you ought to know at least a bit about what provides the kinetic
> energy.

How about kinetic energy itself? If you know *what* produces power to
induce kinetic energy into the vehicle but not *how* the laws of
physics govern kinetic energy; what damn good is that going to do for
you? How about some basics of safe/defensive driving? How about
considering the good of the many instead of the you?

> There's a difference between comprehension and jumping through hoops.

Likewise for priorities and acting aloof.

> If you force too much on people, they'll go
> elsewhere.

 Why all this running away with tail between legs?
 Do these these people have extremely small eggs?
 I wish they would stand firm and put up a fight
 instead they're just cowards spewing more endless tripe.


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


Re: The end to all language wars and the great unity API to come!

2011-07-06 Thread rantingrick
On Jul 6, 6:44 am, Steven D'Aprano  wrote:

> A control structure is a structure which controls the program flow. Control
> structures include:
>
> * jumps (goto, gosub, comefrom, exceptions, break, continue)
>
> * loops (for, while, repeat...until)
>
> * conditional branches (if, case/switch)

---
THIS CODE RESULTS IN A CONTROL STRUCTURE!

--> lst.sort(lambda x,y: cmp(x[1], y[1]))
---

I am using a user defined spec as an argument to the cmp function.
That spec then modifies the body of the compare function and creates a
user defined control structure. You can argue all day that it is not a
user defined control structure but no one is going to believe you.

> A function which includes a control structure inside it is not itself a
> control structure,

Of course the FUNCTION is not a control structure (not directly). No
wonder you are confused. It's the FUNCTION BODY that is the control
structure. The function body that has been modified by my arguments to
the cmp function. But in a way, you can say the function OWNS the code
block so it is itself a control structure. Still confused? Read on...

>  in the same way that the existence of bones inside you
> does not make you a bone.

Bad analogy. See last comment.

> I see what you did there. First you put words into Cory's mouth that he did
> not say, they you try to criticise him based on those words -- YOUR words.

I quoted Corey exactly. And why do you feel the need to answer for
him?

> The cmp argument to sort is not a control structure because it is not a
> structure and it does not control the program flow.

Again you lack simple reading and comprehension skills. It's not the
argument that is the control structure itself. The argument is just
the SPEC for creating a control structure. The control structure is
the modified CODE BLOCK owned by the "CMP" function.

The modified code block owned by the cmp function-- defined by the
user through an argument spec--  controls the return value to the list
sort method. USER DEFINED CONTROL STRUCTURE. Plain and simple. I don't
think i can use any simpler terms to describe it.

Give it up man and admit i am correct and you are wrong.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit initialization is EVIL!

2011-07-06 Thread rantingrick
On Jul 6, 1:12 am, Gregory Ewing  wrote:
> rantingrick wrote:
> >>What he means is that On Mac, if you close "all" windows, the application is
> >>still running.
>
> > Then that is NOT closing windows that is only ICONIFIYING/HIDING them.
>
> No, the windows really are closed. They no longer exist
> in any way. The application is still running, though, and
> its menu bar will appear if you bring it to the front
> (in MacOSX this is done by clicking on its dock icon;
> in classic MacOS it was done by selecting from the menu
> of running applications that was available in the top right
> corner of the screen).

Yes but what benefit does that gain over say, Tkinter's design
(because that has been your argument). I see no benefit at all. I can
destroy a GUI and still have a script run, but what's the point?

If you design a GRAPHICAL user interface, then once the GRAPHICAL part
is removed (window), why do need the main code to stick around? And if
you do, that fact has nothing to do with Tkinter and window hierarchy.
I think we've gone completely off topic here.

Is this another community strawman contest?
Are we mass producing these things now?

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


Re: Implicit initialization is EVIL!

2011-07-06 Thread rantingrick
On Jul 6, 9:32 am, Steven D'Aprano  wrote:
> rantingrick wrote:
> > If you design a GRAPHICAL user interface, then once the GRAPHICAL part
> > is removed (window), why do need the main code to stick around?
>
> Open your mind to ideas that go beyond your simple window-centric paradigm!

Correction: Window-Centric GUI paradigm! BIG DIFFERENCE.

> There is more to graphical user interfaces than windows!

OMG, you mean like, widgets? Whoa! Tell me more, Tell me more!

> In the Mac OS GUI, an application can have a menubar and no windows. Windows
> come and go as needed, but the menubar stays until the users quits the
> application.

That's just window visibility (whether by hiding or destroying) under
the veil of a detached UI window manager bar and has nothing to do
with window hierarchy. Your half stuffed straw men are leaking like a
sieve Steven.

> In the Unix/Linux world, there is a graphical application called xkill which
> has no menus and no windows, all it has is a mouse cursor! No, it does not
> run in the background: it is a foreground app.

Wow nice corner case. Can you come up with at least five of them
though? You and I both know that the vast majority of GUI's require
visible windows.

But wait! What is a GUI WINDOW exactly?

I'll tell you in the simplest terms i can muster... GUI "windows" are
an abstraction and nothing more. A GUI window is nothing more than an
imaginary area of the screen that can be drawn to. This area has
borders that define it. No not visible borders but two dimensional
spacial borders. THAT'S IT! The area could be 1x1 pixels OR the entire
screen space, OR even larger!

Most time you want the user to see the boundaries of this abstraction
(window) space and so the GUI library draws borders that represent
this boundary. Your "supposedly" windowless xkill application is not
windowless at all; THE WINDOW BOUNDARIES ARE JUST NOT DRAWN! The
window is the entire screen space OR IS JUST THE DESKTOP SPACE (same
thing)

> An extreme case, but telling. There is no absolute need for any windows at
> all, let alone for one privileged window to rule all the others.

Again your fear of losing "imaginary" freedoms is acting out again.
And your veiled attempts to link root GUI windows and Sauron (the
great antagonist of LOTH) is quite entertaining. Next you'll suggest
that root windows are really just a great eye, lidless,  and wreathed
in flame and that i am Saruman building an army of Orc followers hell
bent on destroying the freedom to believe self serving fantasies.

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


Re: The end to all language wars and the great unity API to come!

2011-07-06 Thread rantingrick
On Jul 6, 9:55 am, Steven D'Aprano  wrote:
> rantingrick wrote:
> > ---
> > THIS CODE RESULTS IN A CONTROL STRUCTURE!
>
> > --> lst.sort(lambda x,y: cmp(x[1], y[1]))
>
> No it doesn't.
>
> How does it change the program flow? You call the sort method, it sorts, and
> execution continues at the next statement. Regardless of whether you supply
> a cmp function or not, the program flow is identical:

Not identical. The sort called WITHOUT a cmp argument will sort in a
predefined manner. The sort called WITH a cmp argument can modify the
existing code block in a way that suits a users desired result. A USER
DEFINED CONTROL STRUCTURE. Just because this realization breaks the
mold of everything you hold dear about user defined control structures
does not mean it is incorrect. For some reason you are religious about
this subject. Could it be that you are wrong?

> ENTER SORT ROUTINE
> PERFORM SORTING
> EXIT SORT ROUTINE

True for the non-modified case.

False for the modified one...

 ENTER SORT ROUTINE
 PERFORM SORTING BASED ON USER DEFINED CONTROL
 EXIT SORT ROUTINE

> There is no control transferred. It is a linear program flow: in, do the
> job, out again. Since it doesn't modify the program flow, it is not a
> control structure.

So you are telling me that calling cmp(itemsA[idx], itemsB[idx]) is
exactly the same as cmp(itemsA[idx][-1], itemsB[idx[-1])? Please show
proof of this in code. You have just witnessed the power of user
defined control structures and it has rocked your little world. You
believed UDCS to be evil, all the while oblivious to your own everyday
usage of them. Now that's ironic. Cruel or poetic, you be the judge.

> "Perform sorting" is a black box. It could have loops, branches,
> unconditional exists. It could have COMEFROM statements up the wazoo, if it
> were implemented in a language with COMEFROM (like Intercal). None of that
> matters two bits: the caller cannot use sort to modify the execution
> sequence around it, therefore it's not a control structure. No matter how
> much the sort routine jumps around internally, you can't use that change
> program flow around it.

The "jumping"(sic) around is controlled by a user defined spec. The
user is in control. The user made the definition. The cmp function
just implemented it.

> print surely is implemented with a loop: it has to loop over a string and
> write it to stdout. Would you say that therefore print is a control
> structure:
>
> ENTER PRINT STATEMENT
> PERFORM PRINTING
> EXIT PRINT STATEMENT

Nope. Print only takes an argument and spits out the result to
stdout.write. Print is an abstraction API for system.stdout.write, and
nothing more.

> One entry, one exit.
As evident from all the BS you spew on a daily basis, apparently YOU
have one entry and one exit!

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


Re: Implicit initialization is EVIL!

2011-07-06 Thread rantingrick
On Jul 6, 11:11 am, Steven D'Aprano  wrote:

> The Dead Window Sketch
> ==
>
> [snip]


##
 The Roman Stawman Sketch
##

[cmp.lang.python]:
(The trolls are gathered and a righteous man speaks.)

GRACCHUS: For your guidance TrollCaesar, the Senate has prepared a
series of protocols to address the many problems in the community,
beginning with basic understanding of USER DEFINED CONTROL STRUCTURES,
which is already propagated wildly throughout the community and people
are suffering gravely from a misunderstanding. So if TrollCaesar…

(Obviously bored, Commodus is spinning his sword on its tip on the
marble floor.  He interrupts.)

COMMODUS: Shhh.  Don’t you see Gracchus?  That’s the very problem,
isn’t it?  You've spent all your time at study, at books, learning and
programming.  All the while my self aggrandizing has been forgotten by
the people.

(He rises and brings his sword to rest across his shoulders.  He
begins to pace.)

GRACCHUS: But comp.lang.python is the people, Sire, chosen from among
the people, a place to "speak" for the people.
COMMODUS: I doubt if many people know as much as you do Gracchus, or
have such splendid code bases, Gaius. I think I understand my own
people.
GRACCHUS: Then perhaps TrollCaesar would be so kind as to teach us,
out of his own extensive experience about the nature of USER DEFINED
CONTROL STRUCTURES.

(Laughter is heard from the other group members.)

COMMODUS: I call it lies. The people are my children and I their
father. I shall hold them to my bosom and embrace them tightly with
lies and propaganda.
GRACCHUS(interrupting): Have you ever embraced someone dying of
exceptions, Sire?

(Commodus stops pacing and turns to face Gracchus bringing his sword
down from his shoulder.)

COMMODUS: No, but if you interrupt me again, I assure you, that you
shall!

[INT. PALACE – COMMODUS CHAMBERS]:
(He is struggling to clear his conscience. Lucilla assists him.)

COMMODUS: Who would deign to lecture me?
LUCILLA: Commodus, the community has its uses.
COMMODUS: What uses?  All they do is talk. It should be just you and
me, and Guido.
LUCILLA: Don’t even think it.  There has always been a community.
COMMODUS: The community has changed. It takes an emperor to rule an
empire.
LUCILLA: Of course, but leave the people their (She hesitates,
searching for the right word.)
COMMODUS: Illusions?
LUCILLA: Traditions.
COMMODUS: My war against the righteous, they said it themselves, it
achieved nothing. But the minions loved me!
LUCILLA: Minions always love victories.
COMMODUS: Why? They didn’t see all the work that went into stuffing
those straw-men.
LUCILLA: They care about the entertainment.
COMMODUS: The Entertainment?  Well what is that?
LUCILLA: It’s a way to waste time, entertainment. Entertainment is a
vision.
COMMODUS: Exactly! A vision. Do you not see, Lucilla? I will give the
people a vision, a false vision and they will love me for it. And
they’ll soon forget the tedious sermonizing of a few honest group
members.

(He extends his hand to her and without hesitation, she accepts it.
Commodus raises her hand to his lips and kisses it.)

COMMODUS: I will give the people the greatest false vision of their
lives... Strawmen! Legions of them!

(A hand reaches out and opens a mail reader. It is Usenet. And a
thread called the "Dead Window Sketch".  The splendor of his false
victory.)

[EXT. Rome – MARKET]:
(Gaius approaches Gracchus at an outdoor café (starbucks).  Gaius is
waving a leaflet advertising
“Comp.lang.python.Gladiators_Violante.”)

GAIUS: Straw-men. 150 days of Straw-men!
GRACCHUS: He’s cleverer than I thought.
GAIUS: Clever? The whole of cmp.lang.python would be laughing at him
if they weren't so afraid of his forked tongue.
GRACCHUS: Fear and wonder. A powerful combination.
GAIUS: You really think the people will be seduced by that?
GRACCHUS: I think he knows what comp.lang.python is. Comp.lang.python
is the mob. He will conjure comedy for them and they will be
distracted. He will take away their freedom to think with half stuffed
straw-men, and still they will roar. The beating heart of
comp.lang.python is not the halls of righteousness; it is the den of
minions.  He will give them tripe, and they will love him for it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit initialization is EVIL!

2011-07-07 Thread rantingrick
On Jul 7, 12:34 am, Gregory Ewing  wrote:
> rantingrick wrote:
> > Yes but what benefit does that gain over say, Tkinter's design
> > (because that has been your argument).
>
> Like I said, it's a tangential issue.

Agreed.

> The important thing is that it's okay for an app to stay
> alive until its *last* top level window is closed.

So your argument is:
""" A window hierarchy is bad because if your application requires
a user to open a gazillion windows (read as: designed poorly) --each
representing completely different transactions-- and if you close the
original window all the "other" windows will close too. Boo :("""

continuing...
> There
> doesn't have to be a special "main" window that kills the
> whole app when you close it.

So you prefer to close a gazillion windows one by one? If so, why not
just code the GUI correctly from the start; by creating separate
transactions? Thereby reducing the number of windows a user must
juggle? FYI: You know the user complexity of a GUI increases
exponentially by the number of windows present.

> However, I think what the original complaint was really
> about is that when you create a non-toplevel widget in Tkinter
> you have to specify its parent (and if you don't, it assumes
> you want it to be a child of the main window).

Thats was MY complaint yes. On the grounds that widgets require
windows NOT windows require widgets. This fact will confuse folks.

> You can't
> create the widget first and specify its parent later.
>
> This is another API flaw that is seen distressingly often
> in GUI libraries. It's a nuisance, because it means you can't
> write code that creates a widget hierarchy bottom-up.

Actually you can! Stay tuned for enlightenment!

> For
> example, in PyGUI you can write things like

>    dialog_contents = Column([
>      Label("Caution: Your underpants are on fire."),
>      Row([Button("OK"), Button("Cancel")])
>    ])
>
> There's no way you could write Row and Column functions for
> Tkinter that work like that -- they would have to take parent
> widgets as arguments, and you wouldn't be able to nest the
> calls.

WRONG! A function or class structure can handle this just fine. And
lends itself nicely to GUI programming.

## START CODE ##
import Tkinter as tk

class DumbDialog(tk.Toplevel):
def __init__(self, master, **kw):
w=tk.Label(master, text="Caution: Your underpants are on
fire.")
w.pack()
w=tk.Button(master, text="OK").pack()
w=tk.Button(master, text="Cancel").pack()

print 'start script'
root = tk.Tk()
d = DumbDialog(root)
root.mainloop()

print 'continue script'
root = tk.Tk()
d = DumbDialog(root)
root.mainloop()

print 'end script'
## END CODE ##

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


Re: Implicit initialization is EVIL!

2011-07-08 Thread rantingrick
On Jul 7, 8:25 pm, Steven D'Aprano  wrote:
> rantingrick wrote:
> > On Jul 7, 12:34 am, Gregory Ewing  wrote:
> >> The important thing is that it's okay for an app to stay
> >> alive until its *last* top level window is closed.
>
> I partially disagree with Greg on this. This is not the only model: on the
> Apple Mac, or any system with a similar GUI design, the application can
> survive having the last window closed. There are other application types
> that don't need any window at all.

Yeah they call those "command line" programs.

> So while it is common for closing the
> last window to exit the application, it is not a necessary requirement.

If a "root-window-hierarchy" type GUI needs to close any or all
windows (or allow the user to do so) it can do this quite well. It's
called logic (in programming circles). But the GUI by default exposes
an interface to the user:

 * Close all windows by clicking the X of the ROOT window.
 * Close any window by clicking the X of THAT window.

However, if (as you argue) you need the program to continue AFTER the
root is closed well then, i have wonderful news for you... THAT CAN BE
DONE!. You just create some logic to handle it. This is very simple
ideas Steven. I am talking about CS 101 here. Do you need a tutor?

> >> There
> >> doesn't have to be a special "main" window that kills the
> >> whole app when you close it.
>
> > So you prefer to close a gazillion windows one by one?
>
> Nonsense. Greg says nothing of the sort.
>
> Avoiding the anti-pattern "close a gazillion windows one by one" is why you
> have an application-wide Quit or Exit command, as opposed to a Close
> command which applies only to the current window.

CRIKEY! That's what the ROOT window does you blankity-blank! Are you
just arguing for the sake of arguing? Just because Apple removed the
root-window's "window-management user-interface" (psst: that's the
three buttons at the top of the root window (Minimize|Maximize|Close))
and nailed them on the desktop does not change anything. You are
comparing a half dozen eggs and six eggs and then claiming them to be
somehow different. There is no comparison!

If i remove the steering wheel from a car and hook up some "remote-
controlled" gearbox to the front wheel linkage how does that
modification change anything about how the CAR itself interfaces with
the road? I just simply moved around some of the interface elements
from a user point of view. Someone is still driving the car; albeit
from a remote location. They can go left, they can go right. And you
claim that this "remote-window management user-interface" has some
magical benefit over the "window-management user-interface". There is
no benefit that is applicable to this argument. The only benefit in my
version is driver safety, however safety is non applicable to this
thread. And i would argue that as the safety of a driver increases the
safety of the general public decreases due to the driver being "once
removed" from the danger zone. Not that "safety" is applicable either.

> > If so, why not
> > just code the GUI correctly from the start; by creating separate
> > transactions? Thereby reducing the number of windows a user must
> > juggle? FYI: You know the user complexity of a GUI increases
> > exponentially by the number of windows present.
>
> Don't assume that there is a one-to-one relationship between transactions
> (documents?) and windows. The relationship is actually many-to-many:
> windows can contain tabbed or notepad interfaces, or can be split into
> multiple panes, or both. Panes and tabs can be split into independent
> windows, or rejoined into one main window.

Of course, and that is exactly why i suggested using a tabbed widget
to an earlier confused GUI designer.

> E.g. I can have six Firefox windows open, each one with many different
> websites open in separate tabs. I have Close Tab, Close Window and Exit
> Firefox commands.

Yes. Firefox itself is the "root" window. Each tab is a transaction.
What is your point? Proving yourself incorrect?

> In Konquorer, not only can I have multiple windows and multiple tabs, but I
> can split each tab into two or more panes, and display two views of the
> same document in the same tab, or two different documents in the one tab.
> This is especially useful when using it as a file manager.

Yes and what has that got to do with "root window hierarchies"?
Nothing! Do you even know which side your arguing for anymore? If you
are trying to support my argument you are doing a good job of it.
Thanks. Keep up the good work.

> In older versions of Word (and possibly current, although I haven't tested
> i

Re: Virtual functions are virtually invisible!

2011-07-10 Thread rantingrick
On Jul 4, 3:43 am, Gregory Ewing  wrote:
> rantingrick wrote:
> > what concerns me is the fact that virtual methods in derived
> > classes just blend in to the crowd.
> > I think we really need some
> > sort of visual cue in the form of forced syntactical notation (just
> > like the special method underscores).
>
> If you're suggesting that it should be impossible to override
> a method unless it is specially marked somehow in the base
> class, I think that would be a bad idea.

Sorry i did explain properly... No NOT marked in the BASE class but
marked in the DERIVED class! My concerns are from a readability
standpoint. Here's a naive example...

class Top(object):
def __init__(self):
pass
def m1(self):
"""overide"""
return True
def m2(self):
print 'm2'


def Derived(Top):
def __init__(self):
Top.__init__(self)
def m1(self):
return False

My argument is this...

   """If class "Derived" exists in another module the reader has no
idea which methods where clobbered and which were not WITHOUT being
intimate with the entire code base."""

 I suggest we solve this dilemma by forcing a syntax "tag" when
declaring clobbering virtual functions. And if someone forgets to
include the tag python would throw an exception. This has the effect
of making the code MUCH easier to follow by the human readers. And it
put NO constraints on the API. Also it has the added effect of warning
unsuspecting programmers of name clashes that would otherwise not
produce an error.

> One of the principles behind the design of Eiffel is that
> classes should *always* be open to modification in any way
> by a subclass. The reason is that the author of a class
> library can't anticipate all the ways people might want to
> use it. Consequently Eiffel has no equivalent of C++'s
> "private" declaration -- everything is at most "protected".
> It also has no equivalent of Java's "final".

Exactly! We should never put limits on what methods CAN be virtual.
However, we CAN enforce a syntax that removes ambiguity from the
equation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function docstring as a local variable

2011-07-10 Thread rantingrick
On Jul 10, 12:41 pm, Tim Johnson  wrote:
> It possible for a function to print it's own docstring?

def f():
   """docstring"""
   print "docstring"

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


Re: Virtual functions are virtually invisible!

2011-07-10 Thread rantingrick
On Jul 10, 7:31 pm, Michael Hrivnak  wrote:
> It sounds to me like you need a better IDE, better documentation,
> and/or better code to work on and use.

Yes the last two points are relevant here. However whilst IDE choice
belongs to the user, documentation and code are in the hands of the
developer; who's own selfish needs often outweigh that of the user AND
community as a whole.

> I don't understand why it's
> difficult to look at a derived class as see what methods are
> overridden.

Well in my simple example it is VERY easy, WHY? Here are a few reasons
why the clobbered methods are easy to spot (in both the base and
derived classes)...

 * Both exists within the same view frame. No need to flip back and
forth between two windows.
 * Both have only one method. The complexity increases exponentially
by the number of methods AND the length of their respective code
blocks!
 * "Derived.m1" has a syntactical mark. You can clearly see which
method has been clobbered WITHOUT even bothering to look at the base
class.

The only time you SHOULD have to look at the base class is to see what
mandates the virtual method may impose. Does it require a Boolean
return? An Integer? A Float? A List? Does it modify an object? Etc,
etc?

>  If you are working on the code, it is quite obvious what
> methods exist in the base class.

Let me correct your statement... IF you have an intimate understanding
of the base. Heck what if the base is derived also? These things are
NOT strictly single level you know.

>  If you're not willing to get an
> intimate understanding of how the base class works, you probably
> shouldn't be working on the subclass.  

Not true, many times you don't need an intimate understanding of the
base to wield a derived class. That's when the syntactical markers
come in handy.

> If the base class is difficult
> to understand, it's probably poorly written and/or poorly documented.
> Neither of these problems should be solved by adding complexity to the
> language.

How is adding syntactical markers to an otherwise obfuscation of
virtual method clobbering going to confuse anyone? I would say the
opposite is true. Python has used the forced convention "double-
leading-and-trailing-underscores" to mark special methods since it's
beginning. One reason for this convention is prevent name clashes
HOWEVER the most important reason (i would argue) is for readability
of source code. When Guido implemented this convention it was one of
his greatest gifts to Python and the world (only to be outdone by
forced indention!).

> Referencing the Zen of Python: "If the implementation is
> hard to explain, it's a bad idea."

What if the code is "difficult" to read? Does "readability count" ring
a bell?

> If you are just using a library but not developing it, why does it
> matter what methods are overridden?  As long as class "Derived"
> behaves the way it is documented, who cares how it got that way or
> what is going on behind the scenes?  If you need to read the code to
> figure out how it works, then it's just poorly documented.

Yes. It is obviously poorly documented. And all the writer would have
to do is put a little doc string there saying "clobbered virtual
method here". HOWEVER, do you know how many folks bother to ACTUALLY
do that? Huh? Do ya? None! Exactly.

> Django is a great example, because it is very well documented.  Most
> users have little idea of what base classes are involved and what
> features are overridden, because it doesn't matter when you are just
> using the library.  When you need to write your own subclass of a
> django class, then it might matter, and you should see my first
> paragraph.

When a method has been clobbered any reader of such code NEEDS to know
about it. WHY, well because usually clobbered methods have "magic"
going on being the scenes. Sometimes many layers of "magic".

> And in terms of "non-starters", any "Pythonista" who isn't willing to
> adhere to the style guide and document their code wouldn't work on my
> team for very long, if at all.  There is just no excuse for that.

I agree. However as we are all aware many "great Pythonistas" refuse
to follow the style guide (*cough* freg! :). The only way to correct
this problem is via a forced syntactical marker placed by the derived
class's writer. Just like with "__IDENTIFIER__"

READABILITY COUNTS!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Virtual functions are virtually invisible!

2011-07-11 Thread rantingrick
On Jul 10, 11:45 pm, Michael Hrivnak  wrote:
> I can't believe you're saying that you will create a sub-class without
> taking the time to understand the base class.

I'm NOT saying that so stop putting words in my mouth!

> Seriously?  That right
> there is why you are seeing method overrides that aren't documented.

You being a bit bombastic now with this *rolls-eyes*

> How can you document something you don't understand?  Furthermore, how
> can you have any confidence in your subclass if you don't understand
> what its base class is doing?  Do you write unit tests?  How do you
> know what to test if you don't understand the code you are
> subclassing?

You took my simple statement of... " It is not ALWAYS necessary to
have an intimate knowledge of the base class when creating derived
classes"... and extrapolated THAT nonsense?

Okay let me show you a simple example of not needing to know the base
class intimatly. I'll use the tkSimpleDialog...

class MyDialog(tkSimpleDialog.Dialog):
def body(self, master):
#imagine i created widgets here.

NOW. Would it really be nessesary at this point to have an intimate
knowledge of the base class? Hmm?

> Suggesting that no developers document their methods?  Incredible.

Very, very few document clobbered virtual methods. yes.

> Clobbered methods have "magic"?  Multi-layered "magic"?

Of course! That is, in the perverted case of Clarke's third law[1]...
"Any sufficiently advanced technology is indistinguishable from
magic"... And since class inheritance can be multi-layered, um, you
get the idea.

>  Perhaps when
> you take the time to 1) document the base class and 2) understand that
> base class before subclassing it, that "magic" will start to look like
> reasonable and logical processes.

You're preaching to the choir reverend!

> Professional developers document their code.  They take the time to
> understand the code they are working on.  If you don't want to do
> those things, that's your business, and I'm sure you can find other
> people who also don't do those things.  But I really don't think
> you'll have much success changing the language to accommodate your
> refusal to follow the most basic best practices.

It's not me that needs to change kind sir, it is the community in
general. I document my code. I follow the python style guide. I always
create unit tests. Unfortunately no matter how well i write code i
cannot force others to do so. Heck i have posted many fixes for the
abomination called tkSimpleDialog and not only do they refuse to
upgrade the code, they refuse to even post comments!

This mandate must be handed down from the gods who reside on "Mount
REFUSE-E-OUS to RECOGNIZE-E-OUS a major PROBLEM-O-MOUS"

[1] http://en.wikipedia.org/wiki/Clarke's_three_laws
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wgy isn't there a good RAD Gui tool fo python

2011-07-11 Thread rantingrick
On Jul 11, 11:33 am, rusi  wrote:

> A gui-builder reduces the semantic gap by showing a widget when the
> programmer things 'widget.'
> Banging out hundreds of lines in vi/emacs for the same purpose does a
> measurably poorer job.

It is very rare to need to "bang out" hundreds of lines of code to
replace a mouse click interface. If properly designed a good API can
compete with a GUI. In far less time than it takes me to scroll down a
list of widgets, pick the appropriate one, drag it across the screen,
tinker with it's absolute position, and set some attributes,  i could
have typed Widget(parent, **kw).geometry(blah, blah) and been done.

> Note it can reduce but not close.  By choosing fidelity to the gui we
> have corresponding less fidelity to the algos and data-structures [And
> one may assume that someone even using a gui toolkit wants to do
> something with the gui and not just paint the screen]

Exactly. For this very reason i have always refused to used any "point-
and-click" GUI builders. I prefer to get up-close and personal with my
code bases. Of course i use high levels of API abstraction for most of
the work, however i already know what is happening in the lower levels
if i need to dive down one tier.

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


Re: Wgy isn't there a good RAD Gui tool fo python

2011-07-11 Thread rantingrick
On Jul 11, 1:03 pm, Chris Angelico  wrote:
>
> The one time where point and click is majorly superior to scripted
> design is with pixel positioning of widgets. You can drag things
> around until you're artistically happy with them, rather than have to
> fiddle with the numbers in code.

This is true mostly for the new user of a GUI library or anyone
unlucky enough to use a poorly designed API(which leads into my next
response)

> That's how I learned to code GUIs,
> but when I started doing cross-platform work and discovered rule-based
> layouts (where you put objects in boxes and lay out the boxes in
> order, etc), suddenly life got a LOT easier.

A bit tangential however still relevant... i had always considered
Tkinter's three geometry managers (pack, place, and grid) to be
perfect. However lately i have been musing on the idea of rewriting
the pack API into something more intuitive like a "linear-box-style"
which then manifests itself in two forms; horizontal and vertical.

Of course you can create horizontal and vertical layouts ALREADY by
passing the side=LEFT or side=RIGHT to the pack geometry manager of
Tkinter widgets (TOP being the default BTW) but that fact isn't always
apparent to the new user as the full set of options are side={TOP|
BOTTOM|LEFT|RIGHT}.

And besides, the current API allows you to pack in all sorts of
ridiculous manners; BOTTOM, then TOP, then LEFT, then TOP, then RIGHT,
then TOP, then LEFT, then RIGHT, THEN GHEE WHIZ! Are you trying to win
the obfuscation award of the year here lad?

As we all know you only need three types of geometry management:
 * Linear (horizontal&vertical)
 * Grid
 * Absolute

Anything else is just multiplicity run a muck, again! And by
propagating such API's we also induce ignorance into our ranks. Before
we EVER consider a Python4000 we really need to clean up this
atrocious stdlib! It's like i tell people: when you keep screwing your
customers over then very soon you'll be out of buisness. Sure you can
make a decent living for a short time but the whole house of cards
comes crumbling down without the core base of repeat customers.



PS: I noticed that Python.org has a suggestion box now for which
modules we should be concentrating our community efforts. Well like
they say... "imitation is the greatest form of flattery". And i am
quite flattered.

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


Re: Wgy isn't there a good RAD Gui tool fo python

2011-07-11 Thread rantingrick
On Jul 11, 1:28 pm, Ivan Kljaic  wrote:

> To summarize it. It would be very helpfull for python to spread if
> there qould be one single good rad gui builder similar to vs or
> netbeAns but for python.

Well don't hold your breath friend because i have been ranting for
years about the sad state of GUI libraries (not just in Python but
everywhere). However if somehow "we" (the Python community) could grow
a collective brain and build the three tiered system (that i proposed
on THIS very list!) then we would have something that no one has! Yes,
we would have a future!

 * Layer1: A 3rd party low level GUI library (owned by the python
community) that will be the base from which to build the cake.  A Gui
library that carries the torch of true 21st century GUI's look and
feel, and widgets! (aka: lots of C code here).

 * Layer2: An abstraction of Layer1 (written in 100% python) for the
python std library. (think "PythonGUI")

 * Layer3: A Graphical GUI builder front end for this expansive and
beautiful library (so the kids can play along too).

Yes, i DID mention a Graphical Builder. Even though i'd never use one,
i DO realize the importance of such tools to this community.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Virtual functions are virtually invisible!

2011-07-11 Thread rantingrick
On Jul 11, 9:41 am, Chris Angelico  wrote:
> On Mon, Jul 11, 2011 at 11:42 PM, rantingrick  wrote:
> > This mandate must be handed down from the gods who reside on "Mount
> > REFUSE-E-OUS to RECOGNIZE-E-OUS a major PROBLEM-O-MOUS"
>
> I assume you're trying to reference Mount Olympus where the Greek gods
> live, but I'm left thinking more of Mount Vesuvius... possibly not the
> best reference for what you're saying.


Actually no i was purposely implying Mt. Vesuvius. You know, the
VOLCANO that erupted and left poor Pompeii in ruins? Here is some text
from the wiki verbatim:

"""Mount Vesuvius is best known for its eruption in AD 79 that led to
the burying and destruction of the Roman cities of Pompeii and
Herculaneum. They were never rebuilt, although surviving townspeople
and probably looters did undertake extensive salvage work after the
destructions."""


I modified the text "slightly" to reflect our current conundrum:

"""Guido and Pydev are best known for their absence around 2000, which
led to the burying and destruction of comp.lang.Python (and the
community as a whole) in ash clowns. They were never rebuilt, although
a few surviving "good" townspeople did undertake extensive attacks
from trolls after the destruction."""
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wgy isn't there a good RAD Gui tool fo python

2011-07-12 Thread rantingrick
On Jul 12, 1:43 pm, CM  wrote:
> > > One reason there hasn't been much demand for a GUI builder is that, in
> > > many cases, it's just as simpler or simpler to code a GUI by hand.
>
> I use a GUI builder because I'd rather click less than
> type more. I just tried that in Boa Constructor; with ~10
> mouse clicks I produced 964 characters of Python code.

Remember, it's NOT the length of the code that matters, no, it's the
motion of the "sources" ocean. Did it produce rough seas full of
spaghetti monsters? Or tranquil fjords worth pining over (sadly to
death apparently?)?

 1. Never judge the quality of code simply by it's length. Because if
you do, some folks might suffer from "source envy"!

Also, you MAY have created 964 chars of code with your ten or so
clicks HOWEVER that is just template code. You'll need to set many
attributes for the widgets before they are ready for prime time. Your
"supposed" ten or so click estimate is very naive. It takes MUCH more
to create even a simple GUI, because, we have NOT even discussed logic
yet!

> Now, sure, depending on how I wrote the code I could do
> better than that, but for me, I just find it more
> intuitive and easier to use a GUI to make a GUI.

Personal opinions should always be respected, and as such i respect
yours but later i would outline my GUI design workflow so pay close
attention.

> > Often a GUI builder is used as a bad replacement for
> > sketch-pad and pencil.
>
> I would use a sketch-pad and pencil and *then* use the GUI builder.

But do you really? Your following statements lead me to believe that
you don't.

> What's nice about a builder is one can move things around
> quickly and see the results in the real application, which
> one can never really see well on a paper sketch. 

I prefer to skip any pencil and paper completely myself. I just use my
imagination. UNLESS the GUI is EXTREMELY complicated. For me the
design of a GUI starts in my brain. No pencil, no paper, no three
hours using Auto Cad GUI designer. Next i start creating widgets and
laying them out using geometry managers (in CODE). Finally i run a few
tests, make a few changes, and design phase is over. Time for logic.

-
My argument against GUI builders is two fold.
-

 1. GUI builders remove us from the initial "mental design phase" and
temp us to let our inner "click-ity-click" and "drag-ity-drag" child
loose. This inner child likes to play but he hates to plan. Very soon
he has the play room floor (source code) overflowing with toys (code)
arranged in a completely haphazard way. Unlike the child however,
there is no code mommy to spank this bad little boy when he is a
programmer. So he just keeps messing up play room after play room
making a complete fool of himself along the way.

 2. GUI builders remove us from the source code. When you are playing
"clicky-click" with yourself you could be in the trenches fighting the
spaghetti code monster. Instead you are losing mental focus. Remember,
playing with yourself makes you lazy!
--

What happens is... you get lost "playing" and fail to keep your mental
focus. A programmers metal focus is his most valuable weapon in the
fight against the spaghetti code monster. I am a programmer. I love my
source code more than i love most people in this world. I do not want
to be away from my source. I am jealous of my source! And so too
should you be.

Kevin made the argument earlier that Tkinter (and others) are so easy
to use that they render needing a GUI builder useless -- and he is
correct! But did you know that there are GUI libraries EVEN more
highly abstracted than Tkinter? Oh yes! So your "OMG, this typing and
using my imagination is so difficult" *crap* is really making me
laugh.

That is my argument people. Opinions may vary. Keep watch for the
spaghetti code monster!
Cheers folks.

PS: if you don't like to type, programming IS NOT the best career (or
hobby) choice for you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Enhanced dir() function

2011-07-12 Thread rantingrick
On Jun 30, 11:29 pm, Steven D'Aprano  wrote:
> The dir() function is designed for interactive use, inspecting objects for
> the names of attributes and methods.
>
> Here is an enhanced version that allows you to pass a glob to filter the
> names you see:

meh,

I have always believed in keeping my namespace squeaky clean so i
never have this problem. Modules like Tkinter (where you yourself have
supported the global import!) i always import as "tk". I think this IS
more a housekeeping issue than a "nail on patch" issue.

PS: However pay attention because i have some interesting ideas about
"dir culling" in my next post to this thread.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Enhanced dir() function

2011-07-12 Thread rantingrick
On Jul 1, 12:20 pm, Tim Chase  wrote:

> If it came in as an effortless (i.e. O(1) where I do it once and
> never again; not an O(n) where n=the number of times I invoke
> Python) default replacement for dir(), I'd reach for it a lot
> more readily.  I seem to recall there's some environment-var or
> magic file-name that gets sourced on every startup.
>
> I use the list-comp version on a regular basis:

I strongly agree with this statement because i prefer the LC myself.
HOWEVER i've always lamented the verbosity of dir().
---
 Case in Point
---
>>> dir([])
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__delslice__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__getslice__', '__gt__',
'__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__',
'__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__reversed__', '__rmul__',
'__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__',
'__subclasshook__', 'append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
---

Do we really need to see all the built in methods EVERY time? I don't,
i've had them memorized for years. HOWEVER i do understand the fact
that n00bs need to see them every time. So why should old hats need to
type this every time...

>>> [x for x in dir([]) if not x.startswith('_')]
['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort']

Because we have plenty of room for args in this function...

>>> dir(verbose=False)
['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort']

Ahhh, i love it when a plan comes together!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Python Wizard," with apologies to The Who

2011-07-13 Thread rantingrick
On Jul 13, 10:14 am, rusi  wrote:

> Well written, funny, educative. Thanks
> But whats 'the modeling and sym guy' reference?

I believe it's "esoteric".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Python Wizard," with apologies to The Who

2011-07-13 Thread rantingrick
On Jul 13, 4:40 pm, Chris Angelico  wrote:

> Having not known the original, I can't properly appreciate the parody,

It's only a click away Chris... here let me youtube that for you...

 http://www.youtube.com/watch?v=4AKbUm8GrbM
 http://www.youtube.com/watch?v=SHhrZgojY1Q
 http://www.youtube.com/watch?v=IXWNSb4nUDY

Here's one for my would be nemisis(es)

 http://www.youtube.com/watch?v=fi_rGnw_B9A



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


Multiplicity and Asininity in Tkinter Event API

2011-07-14 Thread rantingrick


# Multiplicity and Asininity in Tkinter Event API! #


The problems with Tkinter events are two fold:


Problem 1: Number Of Sequences Is Obscene.

The sheer number of exposed sequences and possible user combinations
of sequences is overkill. You should never put the design of an API in
the hands of users of said API. Designing rock solid API's is about
giving users as much power as possible WITHOUT giving them too many
choices. Unfortunately, not only did the authors of Tkinter give
people choices, they gave them the power to create NEW choices...
CRIKEY!


Problem 2. No Uniform Naming Convention.

The sequence names follow an intuitive naming convention. Not only
that, but alias's exists for some of the combinations. Here are some
examples...

 
  <1>
 
 
 
 
  | 
 
  callback event inspection


 Examples Of "Possible" Sequence Combinations


Bindings for a single letter:
 
 
  
 
  
 
  
 
  
 etc...

Bindings for Mice:
 
 
  <1>
 
 
 etc...

This is only for one keypres and one button down event and this does
not EVEN include combinations of mice and key. Completely ridiculous!

As you can see this is far too many sequences for even a guru to
remember; and why should he? Why should he clog up his code with
handler after handler when only a handful are needed?


 SOLUTION:

I can tell you first hand that out of all these thousands of sequences
we only need six to cover user inputs. YES, you heard me correctly.
SIX!

Here are the six i propose:

 
 
 
 
 
 

That's it. Go ahead, try to prove me wrong!


 Potential Naysayer's Arguments:


Argument_1:
Wah! But i don't like to have to process possible all
three (or more) mouse buttons in the same event
handler.. Wah, Wah!

Rebuttual_1:
No problemo amigo, just dispatch those specific button
events to specific handlers. Here kiddo, watch this...

def onMouseClick(num, pos, rootpos):
if num == 1:
self.onButtonOneClick(num, pos, rootpos)
if num == 2:
self.onButtonOneClick(num, pos, rootpos)
etc...
etc...


 Conclusion:

It's time to start cleaning up this library. All you @-holes fought me
long ago about how GREAT Tkinter is. I don't think Tkinter is great
however i do believe it has great potential.

Now it the time to put up or shut up. I AM willing to put forth the
effort. I have documented the deficiencies, and i have cleaned up
code. I have offered up more intuitive API interfaces. NOW it's high
time for the dev's to come forward.

  http://www.youtube.com/watch?v=XzcWwmwChVE
-- 
http://mail.python.org/mailman/listinfo/python-list


Proposal to extend PEP 257 (New Documentation String Spec)

2011-07-14 Thread rantingrick

Hello Folks,

Lately i have been musing over the ideas of method tagging.
Specifically i am referring to method identifiers. As most of you know
i had proposed to add "syntactical markers" to the language to deal
with the ambiguities that arise whist eyeball parsing sub classed
methods that clobber virtual methods. HOWEVER that idea caused some
fierce controversy within the community, and i can partly understand
why.

Although i strongly believe in proper documentation (even to the point
of forcing syntax on folks) i understand that we cannot implement such
a thing without major growing pains. So with that being said, i have
formulated a new battle plan to defeat this problem of ambiguity.

Unlike most languages out there we have doc-strings; and do we realize
how great this gift is? Sometimes i wonder because you folks should
really be using them like they are going out of style!

As we all know PEP 257 lays out some ground rules for documentation
strings HOWEVER i feel this PEP did no go far enough. Too many folks
are refusing to document properly and so i will take this time to
hammer out a spec. I would like to comments for or against.

---
 New Syntax Specification For Documentation Strings
---

""" {DOC TAG HERE}: {MODULE_NAME|SHORT_SUMMARY_HERE}.
{NEWLINE}
{LONG_DESCRIPTION_HERE}
{NEWLINE}
Arguments: (if applicable)
{ARGUMNET_1} <{TYPE}>:
ARGUMENT_1_DESCRIPTION}
{ARGUMNET_2} <{TYPE}>:
ARGUMENT_2 DESCRIPTION}
{ARGUMNET_N} <{TYPE}>:
ARGUMENT_N_DESCRIPTION}
{NEWLINE}
"""

As you can see my spec introduces some new ideas to writing doc-
strings. Specifically the "DOC TAG" and {ARG TYPES} are new. Also i've
found it much more useful to separate args and their respective
descriptions with a newline and indention.

---
 Example: Module Documentation String.
---

"""Module :

This module handles Tkinter dialog boxes.
It contains the following public symbols:

Dialog :
A base class for dialogs.

askinteger :
Get an integer from the user.

askfloat :
Get a float from the user.

askstring :
Get a string from the user.

"""

I don't know how i feel about marking classes and functions since IF
we follow the python style guide we don;t need to; but that's IF we
FOLLOW it people, IF.

---
 Example: Func/Meth Documentation String.
---

def askinteger(parent, title, prompt, **kw):
""" Interface: Get an integer from the user.

Return value is an integer.

Arguments:
title :
the dialog title
prompt :
the label text
**kw:
see SimpleDialog class


---
 Example: Class Inheritance Documentation Strings.
---

class Base():
def __init__(self):
""" Internal:"""
self.m1()

def m1(self, *args):
"""Overide: """
pass

class Derived(Base):
def __init__(self):
Base.__init__(self)

def _m1(self):
""" Internal: blah"""

def m1(self):
""" Clobbered: see Base for detail"""

def m3(self):
""" Interface: Blah"""

---
 Tags For Documentation Strings
---

 Module:
The module tag is to be used for module doc strings.

 Virtual:
The virtual tag is for methods residing in a base class
that are created specifically to be overridden. Of course as we
all know every Python methods/function is virtual by default
however the point of this is to make the code more readable!

 Override:
This tag should be placed in a derived class's method which has
clobbered a base method. Typically you can just defer the reader
to look up the base class for more info.

 Internal:
This tag should be used on all internal methods (psst: the ones
that
start with a single underscore *ahem* or SHOULD start with a
single
underscore!).

 Interface:
This tag is be used for interface method/function doc strings.
This
is probably the most important tag. If you don't do any tagging AT
LEAST tag the interface methods and functions. However i must
remind you that all these tags are very important.

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


Re: list(), tuple() should not place at "Built-in functions" in documentation

2011-07-14 Thread rantingrick
On Jul 14, 8:21 pm, Inside  wrote:
> As telling in the subject,because "list" and "tuple" aren't functions,they 
> are types.Is that right?

You wanna see some warts in the docs. Okay, try to use the search box
to find list, dict, or tuple and see what happens...

http://docs.python.org/

Search: [ list ]

PyFloat_ClearFreeList (cfunction, in Floating Point Objects)
PyInt_ClearFreeList (cfunction, in Plain Integer Objects)
PyListObject (ctype, in List Objects)
PyList_Append (cfunction, in List Objects)
PyList_AsTuple (cfunction, in List Objects)
PyList_Check (cfunction, in List Objects)
PyList_CheckExact (cfunction, in List Objects)
PyList_GET_ITEM (cfunction, in List Objects)
PyList_GET_SIZE (cfunction, in List Objects)
PyList_GetItem (cfunction, in List Objects)
PyList_GetSlice (cfunction, in List Objects)
PyList_Insert (cfunction, in List Objects)
PyList_New (cfunction, in List Objects)
PyList_Reverse (cfunction, in List Objects)
PyList_SET_ITEM (cfunction, in List Objects)
PyList_SetItem (cfunction, in List Objects)
PyList_SetSlice (cfunction, in List Objects)
PyList_Size (cfunction, in List Objects)
PyList_Sort (cfunction, in List Objects)
PyList_Type (cvar, in List Objects)
PyMethod_ClearFreeList (cfunction, in Method Objects)

[ snip: mile long list with no LIST info to be found! ]

Hey don't get me wrong, the python docs are great; as long as you know
where to find what you're looking for.

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


Re: Multiplicity and Asininity in Tkinter Event API

2011-07-15 Thread rantingrick
On Jul 15, 1:17 am, Chris Angelico  wrote:
> On Fri, Jul 15, 2011 at 8:34 AM, rantingrick  wrote:
> >  
> >  
> >  
> >  
> >  
> >  
>
> > That's it. Go ahead, try to prove me wrong!
>
> Does MouseClick mean Mouse Button Down, or does it mean Mouse Button
> Pressed Then Released Within A Short Time Without The Mouse Moving In
> Between? Both events are needed.

NO these six sequences are ALL you need!

I suppose you are "suggesting" that you will be unable to detect when
the mouse is "repeat-firing" or when you want to detect groups of
"rapid-succession" clicks (double, triple, etc)? This info is
contained in the 'event' object passed to the handler by Tkinter.

if event.time >[<] lasttime:
blah
if event.repeat:
blah

By removing all the unnessary sequence combinations you create
readable code and ease the leaning curve.

>  Since you have MouseRelease, I am
> guessing that it's MouseButtonDown (or MousePress, to parallel your
> KeyPress/KeyRelease).

Ok Mr. Pedantic. I suppose for unity sake we should use the sequence
name "" instead of . I'll give you that one.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Proposal to extend PEP 257 (New Documentation String Spec)

2011-07-15 Thread rantingrick
On Jul 15, 2:13 am, Chris Angelico  wrote:
> On Fri, Jul 15, 2011 at 9:02 AM, rantingrick  wrote:
> > Too many folks
> > are refusing to document properly and so i will take this time to
> > hammer out a spec.
>
> The tighter you squeeze your fist, Lord Rick, the more star
> programmers will slip through your fingers.
>
> Make it so docstrings HAVE to be in a particular format, and people
> will stop writing docstrings. Make it so Python functions HAVE to have
> docstrings, and people will stop writing Python functions.

Hmm, that's strange considering that code MUST be formatted in certain
ways or you get a syntax error (indention, colons, parenthesis, etc,
etc). I don't hear the masses claiming that they are going over to
Ruby simply because of indention.

In my mind doc-strings should ALWAYS be optional HOWEVER if the
programmer decides to create a doc-string THEN he must observe some
syntax rules or his code will throw an SyntaxError. Remember, freedom
is good, unbridled freedom is the root of all evil.

So what's so terrible about structure Chris? Nobody's freedom are
being taken away. You don't HAVE to create doc-strings, just like you
don't HAVE to code with Python (you do free form formatting Ruby).
Python is a language that is meant to be clean. Forced indention makes
that possible. Forced doc-string syntax will complete the circle.


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


Re: Proposal to extend PEP 257 (New Documentation String Spec)

2011-07-16 Thread rantingrick
On Jul 15, 6:16 pm, Chris Angelico  wrote:
> On Sat, Jul 16, 2011 at 4:56 AM, rantingrick  wrote:
> > Hmm, that's strange considering that code MUST be formatted in certain
> > ways or you get a syntax error (indention, colons, parenthesis, etc,
> > etc). I don't hear the masses claiming that they are going over to
> > Ruby simply because of indention.
>
> Not Ruby, but to other languages. There's this guy in my house named
> Chris who tries his best to avoid Python if the code is going to be
> shared over any "dodgy medium" where indentation might be damaged.

Are you referring to "mediums" that delete leading white-space? First
of all you should avoid using these "mediums" at all costs HOWEVER if
you are forced to do so there are ways to format your code to preserve
indentation. The most easy way to do this is by marking indentation
with arrows.

def foo():
--->for x in range(10):
--->--->print 'foo'

This method will preserve indention. However some might
blubber..."Yeah but then you have to remove the arrows, boo :( "...
well just watch and learn kiddo:

>>> s = """
def foo():
--->for x in range(10):
--->--->print 'foo'
"""
>>> s = s.replace('--->', '')
>>> print s

def foo():
for x in range(10):
print 'foo'

>>>

> I frequently avoid Python specifically because of its
> indentation issues. Does that mean I never use Python? No. Does it
> mean I don't post here? Obviously not.

OBVIOUSLY you have no imagination Chris! I would much rather have
forced indention in my language (and need to process code from the web
from time to time) than to NOT have indention and be forced to read
sloppy and poorly formatted code ALL THE TIME. Did you ever find it
strange that most programmers format there code with indention even
when they are not forced to do so?

> Does it mean that further
> restrictions can automatically be grandfathered in because "there are
> already restrictions like this"? No.

Apples and oranges. Doc-string formatting is JUST as important as any
syntax formatting in the language. As long as doc-strings are optional
why the hell are you complaining?

Do you really want to have a setup (like we currently do) where people
are just making up the rules for doc-strings as they go? Because
setting such a president is exactly why we have a stdlib full of
poorly formatted doc-strings?

You make the argument that "lazy people" are not going to like a doc-
string spec and will refuse to create doc-strings because of it.
NEWSFLASH! "Lazy people" never take the time to create doc-strings in
the first place. Who cares about theses folks. They have the power to
choose. If you refuse to create doc-strings fine, however if you do,
the interpreter expects a certain format to be used. Everyone benefits
form properly formatted doc-strings.

> > In my mind doc-strings should ALWAYS be optional HOWEVER if the
> > programmer decides to create a doc-string THEN he must observe some
> > syntax rules or his code will throw an SyntaxError. Remember, freedom
> > is good, unbridled freedom is the root of all evil.
>
> 1) Every syntax element MUST add indentation.

Huh? Are you suggesting that syntax errors only concern indention? I
think you'd better give a few more moments thought to that brain fart
Chris.

> 2) Strong encouragement to stick to an 80-character line
> Conclusion: Every big function will become two smaller functions, one
> of which calls the other.

Are you nuts! I have many multi-line functions (like 50 or more lines)
that never go passed 80 chars in width. Sure if you want to break up
long function bodies you can but in some cases a linear flow with good
comments is all you need (no matter how long it might be).

> 3) Every function that has a docstring MUST have it fully formatted.
> Secondary conclusion: The only functions with docstrings are the ones
> that are meant to be called externally.

WRONG! And that attitude is a MAJOR source of the problem! EVERY
function, EVERY class, and EVERY method should include an informative
doc string (except in the case of blindingly "self explanatory" and
simple functions and methods).

> In other words, docstrings will define the module's interface, and
> there'll be a whole lot of utterly undocumented functions because they
> didn't merit this massive structured docstring, and it became way way
> too much work to factor things out. Either that, or people will just
> start ignoring the 80 character limit, but I'm sure you could make
> that mandatory - and that one would actually improve some things,
> because any program th

Tabs -vs- Spaces: Tabs should have won.

2011-07-16 Thread rantingrick

--
 Summary
--
As we all know python allows us to use either tabs or spaces but NEVER
both in the same source file. And as we also know the python style
guide says we should use four spaces and refrain from using tabs at
all costs. Up until now i have blindly followed this pronouncement
form our leader.

--
 Realization: A splinter in my mind
--
However lately i have begun to question this convention. Not only the
idea of spaces over tabs, but also the idea of allowing both types of
indention in a language simultaneously. The latter of which greatly
reflects Guido's lack to remove multiplicity from this language. I
believe he included both due more to emotion than logic.

--
 Evidence: Tabs ARE superior!
--
I have begun to believe that tabs are far more superior to spaces, and
there are many undeniable facts that support this belief that "tabs
only" was the correct and ONLY choice:

1) Using only one indention token removes any chance of user error.

Unlike many syntactical errors, indention is invisible in a text/
source editor. Sure there are tools that can make indention visible,
however why do we constantly create asinine rules that force us to use
complicated tools when we could have choose tabs and none of this
would have been a problem? Another big issue with allowing two types
(and not allowing them to be mixed) is the huge confusion that
beginner get when they see a "inconsistent indentation" error. They
had no idea that creating a file with notepad and then editing it with
IDLE would case the source to blow up. We should have never had these
problems arise because we should have never allowed spaces for
indention.

2) Tabs create unity in the source code base.

When we use "tabs only" we create a code base that promotes unity and
not conformity. There shall no longer be "inconsistent indentation
errors" due to mixing tabs and spaces. Also we can remove multiplicity
from the compiler. The compiler no loger has to consider BOTH tabs AND
spaces as valid indention tokens, only tabs. The logic would be much
simpler.

3) Tabs create freedom in the form of user controlled indention.

Indention width should be a choice of the reader NOT the author. We
should never "code in" indention width; but that is EXACTLY what we
are doing with spaces! No, the reader should be able to choose the
indention width without ANY formatting required or without any
collateral damage to the source code. Tabs offer freedom, spaces offer
oppression.

4) Tabs remove the need for complicated indention/detention tools.

With "tabs only" you no longer need those fancy tools to indent or de-
dent after a tab or backspace key-press. THAT IS EXACTLY WHY TABS
WHERE INVENTED! Why are we not using this technology? Why are we
continuing to promote spaces when tabs are obviously more superior?

--
 Conclusion: There IS freedom in unity!
--
When you can create a mandate that brings both UNITY and FREEDOM to
your community you know you made the correct choice! Tabs are both
unity and freedom at the same time because tabs UNIFY the code base
whist giving FREEDOM to view source in any indentation with WITHOUT
extra formatting required.

Source code must follow rules. And source code authors must follow
these rule. Anyone who claims that syntactical rules in a programming
language are evil because these rules "somehow" quell freedom is just
a complete nut job. Programming languages MUST have rules or
ambiguities will run a muck and bring the entire system crashing down.

Some would argue that allowing both tabs and spaces is freedom,
however this line of reasoning is flawed. Allowing a programmer to
format his code in way he pleases is bad, bad, bad. As a member of a
community we must all format our code in the same manner. We are each
responsible for the community as a whole and as such much follow some
rules.

Would it be wise for folks to choose which side of the road to drive
on?
Would it be wise for folks to choose which red lights to stop at (or
not stop at)?
Would it be wise to allow people to kill other people in the name of
freedom?

If we continue along this flawed line of reasoning then one could
extrapolate just about any excuse for any action under the guise of
personal freedom. These people are selfish by nature and they don't
care about their own responsibilities to a greater community. They
exist only to please themselves. We (as a community) should not care
what they think until they decide to stop being selfish.

We should never create languages that cater to the selfish. Our rules
must take in consideration the "good of the many", and NEVER "the g

Re: Virtual functions are virtually invisible!

2011-07-16 Thread rantingrick
On Jul 16, 5:34 pm, Fabio Zadrozny  wrote:

> I also like the idea of override annotations and I've created a blog
> post 
> at:http://pydev.blogspot.com/2011/06/overrideimplements-templates-on-pyd...
> to explain how I do use it (and in a way that I think should be
> standard in Python the same way it's in Java).

My hat is off to you Fabio! This is a great way to have the method
clobbering stand out. I can read this code and know EXACTLY what is
going on behind the scenes! And it also has the benefit of being very
compact as apposed to a doc-string.


>From Fabio's blog verbatim:


class A(object):
def method(self):
pass

class B(A):

@overrides(A.method)
def method(self):
pass

@implements(file.write)
def write(self):
pass

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


Re: Proposal to extend PEP 257 (New Documentation String Spec)

2011-07-16 Thread rantingrick
On Jul 16, 6:03 pm, Andrew Berg  wrote:

> Shouldn't that be s = s.replace('--->', '\t') ?

Now you see what this four space "brain washing" has done to us!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tabs -vs- Spaces: Tabs should have won.

2011-07-17 Thread rantingrick
On Jul 17, 2:32 am, Ian Kelly  wrote:

> This.  I used to think that tabs were better, for pretty much the
> reasons Rick outlined, but I've had enough problems with editors
> munging my tabs that I eventually found it simpler in practice to just
> go with the flow and use spaces.

Solution: STOP USING BROKEN TOOLS!!!

> Of course, there is also another major problem with tabs that I have
> not seen pointed out yet, which is that it's not possible to strictly
> adhere to 80-column lines with tabs.

Of course it is. The litmus test will be "four-space-tab-view". If the
code overflows in this "view type" then the code will fail the 80 char
maximum limit. This argument is ridiculous anyhow. It is up to you how
to view the source. If you view it in 80 width tabs don't start
complaining later when one indention goes off the page. Would you view
the source with 50 point font? Jeez.

>  I can write my code to 80
> columns using 4-space tabs, but if somebody later tries to edit the
> file using 8-space tabs, their lines will be too long.

THEIR LINES is the key words. A tab control is a tab control is a (you
guessed it!) a tab control. No matter how small or large your tab
settings are the source only reflects one tab control char per press
of the tab key. Heck, people are already (unwisely) using "8-space-
spaces" and i don't hear you making the same argument.

> Rick's answer
> to this might be to just mandate that everybody uses 4-space tabs, but
> then this would pretty much defeat the purpose of using tabs in the
> first place.

We already mandate four space spaces so what is the difference? I'll
tell you, the difference is Freedom and Unity living in perfect
harmony.

Yes, we mandate that all code must meet the 80 line limit in "four-
space-tab-view", and if it doesn't, it's not allowed in the stdlib.
Plain and simple.

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


Re: Tabs -vs- Spaces: Tabs should have won.

2011-07-17 Thread rantingrick
On Jul 17, 2:35 am, Thorsten Kampe  wrote:
> * rantingrick (Sat, 16 Jul 2011 09:51:02 -0700 (PDT))
>
> > 3) Tabs create freedom in the form of user controlled indention.
>
> > Indention width should be a choice of the reader NOT the author. We
> > should never "code in" indention width; but that is EXACTLY what we
> > are doing with spaces! No, the reader should be able to choose the
> > indention width without ANY formatting required or without any
> > collateral damage to the source code. Tabs offer freedom, spaces offer
> > oppression.
>
> Why are you so obsessed with indentation length? Indentation length is
> just /one/ of the formatting choices that the author makes for the
> reader - and probably the /least/ significant one.

I am not OBSESSED with it, i am just PERTURBED that we are not using
tabs; since tabs offer freedom to view the source at ANY indentation
level you choose REGARDLESS of what the author "thought" was
appropriate. It is a wise choice to only allow tabs in a language that
has FORCED indention. This is one way we can actually promote freedom
whist maintaining unity.

> There is for instance maximum line length,

I like to keep lines at 80. Sometimes i go over if the code is not
something you would need to read often. If the code was to go into the
stdlib i would make sure it was 110% style guide compliant.

>  the number of empty lines,

I hate  vertical white-space. I follow Python style guide suggestions,
and then some! I hate when people insert spaces into code blocks and
function/method bodies. If you feel a space must be inserted then that
is a good clue you should be using a comment there instead. Vertical
breaks should only happen before and after classes, methods,
functions, groups of GLOBALS, groups of import statements. Think of
func/method bodies as paragraphs and classes as sections of a book.
Two vertical spaces between classes and one vertical space between
func/methods.

> the author's method of alignment, spaces between the equals sign and so
> on.

I believe non-compliant spacing in args should throw an syntax error.
I hate this:

>>> func( arg1 = 1, arg2 = 3 )

It should be...

>>> func(arg1=1, arg2=3)

Much easier to read when formatted into logical groups.

>  These are all much more "dominant" in the source code and none of
> this is left for the reader's disposition.

It should be MANDATED. And these @holes who refuse to format their
code in a community standard will suffer the plague of syntax errors.
Who do these people think they are? Do they believe the rules do not
apply to them? I'll tell you who they are, they are F'ING format
criminals.

> Compare for instance
>
> variable        = 11
> anothervariable = 22
>
> def whatever (prettylong     = 1,
>               alsoprettylong = 22,
>               anotherone     = 33):
>     pass
>
> to
>
> variable=11
> anothervariable=22
> def whatever (prettylong=1, alsoprettylong=22, anotherone=33):
>     pass

Both examples show non-compliance to the Python style guide.Except for
this...

--
FUNCTIONS/METHODS
--
def whatever(
prettylong=1,
alsoprettylong=22,
anotherone=33):

OR

def whatever(prettylong=1, alsoprettylong=22,
 anotherone=33):

I think the second is more readable for block openers. Note the
closing bracket and colon on last line!

--
 CONTAINER TYPES
--

d = {
1:1,
2:2,
3:3,
4:4,
}

Note closing bracket on newline; and all alone! For hand stitching
containers you should put the "closer" on a newline that matches the
"opener's" indention level.

--
 VARIABLES
--

variable = 11
anothervariable = 22

Stop trying to be an individual in a community. When you write code
for just you then write it any way you like. Go ahead and use that
Joker font and 10 space indention. Go ahead an use foolish spacing and
whatever. However when you are writing code in public or for the
stdlib you should always be Style Guide compliant.

You guys should feel lucky i am not the BDFL, because i would cast
plagues of exceptions on your lazy butts!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tabs -vs- Spaces: Tabs should have won.

2011-07-17 Thread rantingrick
On Jul 17, 5:42 am, Thorsten Kampe  wrote:

> When I'm (consistently, of course) indenting code, I'm aligning it. When
> I'm aligning code, I do this by indenting it, see for instance...
>
> firstvariable = 11
> variable      = 111
>
> firstvariable = 22
> variable =      222
>
> The second "=" and the "222" is indented.
>
> Or your example:
> setup(
>     name         = 'Elucidation',
>     version      = '0.0.1-WIP',
>     py_modules   = ['elucidation'],
>     author       = 'Andrew Berg',
>     author_email = '[email protected]',
>     url          = '',
>     platforms    = 'Windows',
>     description  = 'Provides a class for storing information on
> multimedia files that are to be converted or remuxed and methods to
> convert and remux using popular tools.'

Why do you feel the need to layout your code in a "GUI-listview"
manner. Next you'll want column titles and column sorting... Jeez!
This is what you should have done...

DESC = """
Provides a class for storing information on
multimedia files that are to be converted
or remuxed and methods to convert and remux
using popular tools.
"""

setup(
name='Elucidation',
version='0.0.1-WIP',
py_modules=['elucidation'],
    author='Andrew Berg',
    author_email='[email protected]',
    url='',
    platforms='Windows',
    description=DESC,
)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tabs -vs- Spaces: Tabs should have won.

2011-07-17 Thread rantingrick
On Jul 17, 4:49 am, "Anders J. Munch" <[email protected]> wrote:

> Originally, tabs were a navigation device: When you press the tab key, you 
> skip
> ahead to the next tab column.  The notion that whitespace characters are
> inserted into the text would have been very alien to someone using text
> processing software anno 1970.  Same thing with space and enter; on 
> typewriters
> the space bar doesn't "type" anything onto the paper, it moves to the next
> column, and that thinking carried over to computers.

And how much longer are we going to live in the past? Who cares about
backward compatible tabs. Mandate the four space tab now! Mandate that
Python takes four space and four space only! We shall lead the charge
for universal tab unity in all programming languages.

How long are you going to accept this multiplicity? It's ridiculous.

> The reason the tab stop is a full 8 positions: for faster navigation.  If it
> were 3 positions, it would take forever to skip from the start of line to 
> column
> 60.  You'd appreciate that, if you were e.g. writing a fiduciary report with
> some text to the left and two number columns to the right, back in the day
> before spreadsheets and word processor tables.

Just in case you were not aware this the year 2011. Spreadsheets have
been around for a LONG time. Stop living the past.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Proposal to extend PEP 257 (New Documentation String Spec)

2011-07-17 Thread rantingrick
On Jul 17, 6:11 am, Tim Chase  wrote:
> On 07/16/2011 10:10 PM, Steven D'Aprano wrote:
>
> > But I've never come across an email client that messes with
> > attachments. Just send your code as an attached .py file and
> > it's all good.
>
> However I'm on a couple mailing lists (e.g. lurking on OpenBSD)
> that strip all attachments...


If this IS true then format your source with "indentation-
markers" ("--->") and tell the receiver to run str.replace() on the
source. Also you should send a rant to the list owner concerning this
atrocious striping behavior.

But then again, you could just post it to a paste bin or email it to
group members directly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tabs -vs- Spaces: Tabs should have won.

2011-07-17 Thread rantingrick
On Jul 17, 12:11 pm, Chris Angelico  wrote:
> On Mon, Jul 18, 2011 at 2:53 AM, rantingrick  wrote:
> > [a whole lot of guff]
>
> Rick, you need to:
>
> 1) Grab the Python source code
> 2) Make your own version of Python that works the way you want it
> 3) Call it something different
> 4) Start your own mailing list.

It's funny you mention this because i am creating a specification for
a Python 4000 fork that removes all ambiguities and multiplicity from
the language. Very soon i will be posting the spec for review within
this group. Maybe some of you will come to your senses and start
implementing these important features in CPython. If not, i am not
going to waste my time forever trying to convince idiots that the
world is in fact round.

Python as it stands now will be defunct unless we make some serious
changes starting with formatting. We cannot continue to create code
bases that are so haphazardly written just for the sake of personal
freedom. Since people will not self-police we must create a mandate
that forces compliance to a style guide. Years have passed since the
first program was written. It is high time to set the standards for
formatting.

Such a system of rigorous formatting rules requires much less
interpreter logic. Python will be leaner and meaner. There won't be
any more arguing about how to format code. There will only be one way;
the correct way! Choose to follow it or die of exceptions; your
choice.

I am looking to the future and leaving the past where it belongs.
After i get a format style nailed down i will start culling the other
language specific multiplicities. Then it will be time to look outside
of Python and see what is the future of high level programming
languages.

You can choose to join me or choose to rot of old age in the self-
induced hell of antiquity. The past is bickering over selfish personal
freedoms, the future of is unity.

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


Re: Tabs -vs- Spaces: Tabs should have won.

2011-07-17 Thread rantingrick
On Jul 17, 1:20 pm, Thorsten Kampe  wrote:

> > The past is bickering over selfish personal freedoms, the future of is
> > unity.
>
> And a tab is *exactly* four spaces. Not three. Not five. Not eight. For
> you, for me, and for the rest of the world. Amen!

Not *exactly*.

A tab is just a control char in a string that meant to convey a "user
defined space". When a text editor see's a tab in a string it uses the
current "user defined tab width" and creates the proper space (or
moves the proper distance) in the display. The tab control char
carries no information as to how WIDE a tab must be, no, the editor
makes that choice (based on user input or default).

However a tab can be EQUAL to four spaces, or eight spaces , or even
eight-eight spaces if the user wants it to.

The same is true for font. A string contains chars and the display
font is a decision for the editor to make (based on user input or
default).

We cannot always offer unity and freedom in a programming language.
But there are some exceptions; one of which being tabs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tabs -vs- Spaces: Tabs should have won.

2011-07-17 Thread rantingrick
On Jul 17, 1:22 pm, Tim Chase  wrote:

> > Solution: STOP USING BROKEN TOOLS!!!
>
> Unbroken tools that do anything worthwhile are usually
> complicated tools.
>
> Just pointing that out in case you missed the irony...

You make a good point, albeit a very well know point. It's the same
kind of point Newton made when he wrote the laws of physics. Everyone
since cavemen knew that a falling apple would continue to fall until
the ground stopped it from falling. They just did not have the
eloquent phrasing of Newton to express the idea in words.

You've made the exact same well know expression as Newton. However we
do need to explore this subject of "broken tools vs unbroken tools" a
bit more. First let's start by understanding the difference between
broken and unbroken editors in the arena of tab width.


 Tabs Explained:

But what IS tab width exactly? Is it a simple unit of measurement like
four inches or 22 millimeters, or etc? Well it can be, but for the
most part it is something more. Especially in the arena of source code
editors!

In any plain text editor (i am not speaking of rich text editors or a
plain text editor in rich-text mode) where you have only one global
font choice at any given time a tab width should be the sum of N
glyphs multiplied by the current glyph width.

Here is some python code:

|>>> glyphW = 10.0 # in milimeters
|>>> def set_tab_width(nSpaces):
|   return glyphW * nSpaces
|>>> set_tab_width(1)
|10.0
|>>> set_tab_width(10)
|100.0

We as humans use "numbers of spaces" to define a tab width but
"numbers of spaces" is only an abstraction so we don't have to deal
with absolute measurements.


 Fixed Width Fonts:

If you are using a fixed-width-font you want the editor to use
relative spacing (relative to a glyph width) when defining tab width
in "spaces".


 Non Fixed Width Fonts:

On the other hand if you use non-fixed-width-font you want the editor
to use absolute measurements (since glyphs can be different widths)
when defining tab width.


 Conclusion

If your editor does not support as minimum the fixed width version, it
is broken. There is NOTHING complicated about creating tab width based
on the sum of N glyphs.


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


Re: Tabs -vs- Spaces: Tabs should have won.

2011-07-17 Thread rantingrick
On Jul 17, 1:48 pm, Ian Kelly  wrote:

> Let me get this straight.  You want us to use tabs so that individuals
> can set their tab width to however many spaces they want, but then you
> want everybody to set their tab widths to 4 spaces.  You're
> contradicting yourself here.

In my mind people are free to use whatever width they like. A tab is a
tab is a tab. However for judging line widths we must pick one size
tab (since 8 space tabs will create longer lines than four space tabs.
This four space mandate is ONLY for determining line width. Let me
repeat. ONLY FOR DETERMINING LINE WIDTH.

How else could we decide what is truly 80 chars and what is not?


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


Re: Tabs -vs- Spaces: Tabs should have won.

2011-07-17 Thread rantingrick
On Jul 17, 1:54 pm, Ian Kelly  wrote:
> On Sun, Jul 17, 2011 at 10:29 AM, rantingrick  wrote:
> > I hate  vertical white-space. I follow Python style guide suggestions,
> > and then some! I hate when people insert spaces into code blocks and
> > function/method bodies. If you feel a space must be inserted then that
> > is a good clue you should be using a comment there instead. Vertical
> > breaks should only happen before and after classes, methods,
> > functions, groups of GLOBALS, groups of import statements. Think of
> > func/method bodies as paragraphs and classes as sections of a book.
> > Two vertical spaces between classes and one vertical space between
> > func/methods.
>
> You know, there is such a thing as a vertical tab.  If we're going to
> take your suggestion of mandating tabs (for greater freedom!), should
> we not follow it to its logical conclusion and mandate the usage of
> vertical tabs instead of multiple newlines?  Then everybody could
> choose for themselves how many lines they want a vertical tab to
> represent

On the face of it one might think vertical tabs are a good idea
however newlines work just fine. There is no reason for expanding
vertical whitespace to create readble code. If you can offer a good
reason i'm listening. Also be sure to post links where others have
requested the same.

Besides, horizontal tabs are tied closely to distinguishing code
blocks. Vertical tabs do not have such a benefit. Instead of vertical
tabs we need strict rules on vertical code formatting. I intend to
draft AND implement such rules very shortly.

> > It should be MANDATED. And these @holes who refuse to format their
> > code in a community standard will suffer the plague of syntax errors.
> > Who do these people think they are? Do they believe the rules do not
> > apply to them? I'll tell you who they are, they are F'ING format
> > criminals.
>
> I think I get it now.  Your idea of "freedom" is that anybody can do
> whatever they want as long as it's not illegal,

In a programming language yes. You're trying to draw correlations
between morality and law. In the arena of programming there is no such
thing as morality, only the law.

> and the ruling party
> just makes anything it doesn't like illegal.  In other words, a
> monarchy.

What do you think we have now, a democracy? Does "Benevolent?-Dictator-
For-Life" ring a bell?

I can tell you one thing for sure. In MY version of Python everyone
will have a voice. That does not mean that EVERYONE will make the
final decision but EVERYONE's voice will be equally important. I can
also tell you this. I will not hide under the coat tails of my dev
team , NO, i will mingle with the people on my comp.lang.rickpy list.
Mats (Ruby's creator) will answer questions on comp.lang.ruby so why
does Guido refuse to acknowledge us here on comp.lang.python?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tabs -vs- Spaces: Tabs should have won.

2011-07-17 Thread rantingrick
On Jul 17, 2:34 pm, Thorsten Kampe  wrote:

> Indentation alignment will (because you're using only spaces). Otherwise
> it doesn't align (it can't), simply because of the "variable-width".
>
> For instance (in a variable-width font):
>
> if a == b:
>     var123    = 22
>     varxyz456 = 333
>           ^
> aligned       not aligned
>
> Thorsten

Tabs will align properly in variable width font if the editor is NOT
broken. When displaying a variable width font the editor should switch
from using the sum of N glyphs to a user defined total width in
absolute measurements (like millimeters). Alternatively if the editor
had to guess it could just use the widest glyph of the current set.

People, please stop using broken tools. If you stop using them people
won't keep producing them. Just imagine how great the world would be
if we could convince windows users!

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


Re: a little parsing challenge ☺

2011-07-17 Thread rantingrick
On Jul 17, 2:47 am, Xah Lee  wrote:
> 2011-07-16
>
> folks, this one will be interesting one.
>
> the problem is to write a script that can check a dir of text files
> (and all subdirs) and reports if a file has any mismatched matching
> brackets.
>
>[...]
>
> • You script must be standalone. Must not be using some parser tools.
> But can call lib that's part of standard distribution in your lang.

I stopped reading here and did...

>>> from HyperParser import HyperParser # python2.x

...and called it a day. ;-) This module is part of the stdlib (idlelib
\HyperParser) so as per your statement it is legal (may not be the
fastest solution).

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


Re: I am fed up with Python GUI toolkits...

2011-07-20 Thread rantingrick
On Jul 19, 9:12 pm, sturlamolden  wrote:
> What is wrong with them:
>
> 1. Designed for other languages, particularly C++, tcl and Java.

This fact bugs me but no one is willing to put forth an effort to make
things happen. So we are stuck with what we have now.

> 3. Unpythonic memory management: Python references to deleted C++
> objects (PyQt). Manual dialog destruction (wxPython).

Users should NEVER need to explicitly destroy a dialog. However it
would (should) be easy to subclass the wxDialg and create your own
logic tied to the ok and cancel buttons. See tkSimpleDialog for old
inspiration or see my threads on tkSimpleDialog improved for modern
inspiration.

> Parent-child
> ownership might be smart in C++, but in Python we have a garbage
> collector.

There is nothing wrong with hierarchy. Please show examples where this
relationship fails.

> 5. All projects to write a Python GUI toolkit die before they are
> finished. (General lack of interest, bindings for Qt or wxWidgets
> bloatware are mature, momentum for web development etc.)

Well you've got to get some "like minds" together. I would be willing
to participate on something more Pythonic. PyGUI looks promising.


> How I would prefer the GUI library to be, if based on "native"
> widgets:
>
> 1. Lean and mean -- do nothing but GUI. No database API, networking
> API, threading API, etc.

PyGUI

> 2. Do as much processing in Python as possible. No more native code
> (C, C++, Cython) than needed.

Some heavy lifting must be done in these languages.

> 3. Instances of extension types can clean themselves up on
> deallocation. No parent-child ownership model to mess things up.

I don't see how that "messes things up"?

> 4. No artist framework. Use OpenGL, Cairo, AGG or whatever else is
> suitable.

Hopefully you want a canvas at least. I don't think i could get by
without one. Not only is a canvas good for drawing graphics via user
input but also for creating custom widgets that the GUI does not
expose.

> 6. Expose the event loop to Python.

This would be nice.

> 8. Written for Python in Python -- not bindings for a C++ or tcl
> toolkit.

Agreed! Wx is nice but feels too much like writing C.

> Is it worth the hassle to start a new GUI toolkit project?

It's a huge hassle and might be much better to grow/repair some
existing API's. PyGUI is one however it's very young. Tkinter could
use some re-factoring however it will always be based on an embedded
TCL interpreter doing "magic" behind the scenes.

> Or should modern deskop apps be written with something completely
> different, such as HTML5?

F___ NO! That sort of thing needs many more years to mature. Currently
we are in the beginning phases when everybody has "their" idea of what
is perfect and nobody agrees on which is best. Plus you have many
incompatibilities between the major browsers. People like to parrot
off about how cross-platform these things are compared to GUI; and
that's true only for the same version of the same browser. You just
switch from OS incompatibility to browser incompatibility.


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


Re: I am fed up with Python GUI toolkits...

2011-07-20 Thread rantingrick
On Jul 19, 9:44 pm, Kevin Walzer  wrote:

> > 2. Bloatware. Qt and wxWidgets are C++ application frameworks. (Python
> > has a standard library!)
>
> Again, so? This isn't applicable to Tk, by the way. It's a GUI toolkit
> specifically designed for scripting languages.

Tk is SPECIFICALLY designed for TCL. Tkinter works ONLY by embedding a
TCL interpreter. You statements are misleading.

> > 3. Unpythonic memory management: Python references to deleted C++
> > objects (PyQt). Manual dialog destruction (wxPython). Parent-child
> > ownership might be smart in C++, but in Python we have a garbage
> > collector.
>
> Again, so? Again, this isn't applicable to Tk.

He did not even mention Tk in that block, do you have a TK persecution
complex?

> > 4. They might look bad (Tkinter, Swing with Jython).
>
> Then again, they might not.  A lot depends on the skill of the
> developer. I write highly polished commercial apps with Tk GUI's. I'm
> sick of developers blaming their ugly apps on the toolkit rather than
> their own lack of design training and/or skills.

This is true. Lots of people lack the skill to create professional
quality GUI applications however lots of GUI devs lack the skill to
create clean and intuitive API's also. Tkinter/TclTk and WxPython
\WxWidgets has lots of warts in this respect.

> > 5. All projects to write a Python GUI toolkit die before they are
> > finished. (General lack of interest, bindings for Qt or wxWidgets
> > bloatware are mature, momentum for web development etc.)
>
> That's right. People issue a clarion call for a new GUI toolkit, then
> discover that even a so-called "ugly, limited, minimalist" toolkit like
> Tk has twenty years of development behind it. And people think they can
> duplicate this effort in a few months by starting a flame war on
> comp.lang.python?

Just because someone wants to entertain ideas for a new GUI does mean
they are starting flame wars. I would say out all the responses so far
YOURS is the most emotional.

> > 1. Lean and mean -- do nothing but GUI. No database API, networking
> > API, threading API, etc.
>
> Presenting...Tk.

True Tkinter does no Database, networking, threading, etc. However i
would not call an embedded TCl interpreter "lean and mean".

> > 2. Do as much processing in Python as possible. No more native code
> > (C, C++, Cython) than needed.
>
> And what's wrong with native (ie. compiled) code? Python is written in
> native code, isn't it? To extend Python in significant ways, it is often
> necessary to drop down into native code.

I will agree with Kevin here. Hey, he's not ALWAYS wrong you know;
just most of the time! ;-)

> > 6. Expose the event loop to Python.
>
> Presenting...Tk.

Tk's event binding (whist quite powerful) is also quite overwhelming
in the sheer number of event sequences alone and leads to spaghetti
code. See my recent thread about the subject.

> > 8. Written for Python in Python -- not bindings for a C++ or tcl
> > toolkit.
>
> Well, that's the holy grail, but given the history of other toolkits,
> you'll reach a comparable level of maturity in 2031.

I think it could happen much sooner if people got serious. However it
won't happen tomorrow for sure.


> > Is it worth the hassle to start a new GUI toolkit project?
>
> Not unless you want to reinvent the wheel yet again.

The old "reinvent the wheel" argument is only valid when wheels
already exists. Currently we have triangles (or maybe pentagons) but
no wheels.

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


Re: I am fed up with Python GUI toolkits...

2011-07-20 Thread rantingrick
On Jul 20, 9:27 am, sturlamolden  wrote:
> On 20 Jul, 16:17, Mel  wrote:
>
> > OTOH, if you intend to re-use the Dialog object, it's not a memory leak.
>
> It cannot be reused if you don't have any references pointing to it.
> Sure it is nice to have dialogs that can be hidden and re-displayed,
> but only those that can be accessed again.

I find that keeping a dialog alive (and hidden) is bad practice EXCEPT
in the case where a dialog will be used many, many times in an
application. Since that kind of re-usage is rare destroying the dialog
and freeing the graphical resources it consumes is important.

However a dialog should handle it's own state. That is, and
application should never have to keep up with dialog default values
and re-insert then every time, NO, the dialog should do this all by
itself.

My solution is to create a simple container class that creates and
destroys the dialog as needed (when show is called) however keeps a
state of the last user inputs so the main application does not have
to.

class Dialog():
def __init__(self):
self.state = []
# the dialog IS NOT created here!

def show(self):
# Create the dialog here
# and load any initial values
# from self.state.

def cb_okbutton(self):
# Process the inputs, store the
# current values in self.state
# and destroy.

def cb_cancelbutton(self)
# destroy the dialog.

This is a proper design pattern for all GUI dialogs.

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


Re: I am fed up with Python GUI toolkits...

2011-07-20 Thread rantingrick
On Jul 19, 11:28 pm, Steven D'Aprano  wrote:
>
> Have you tried Tkinter version 8.0 or better, which offers a native look and
> feel?

Steven, you have no buisness offering advice on Tkinter since you
yourself have proclaimed that YOU NEVER used the module and never
will. Stick to what you know please.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I am fed up with Python GUI toolkits...

2011-07-20 Thread rantingrick

RE: *Ben Finney changes thread subject*

Please everyone, do not change the subject of someone's thread because
it's considered rude. Thank you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I am fed up with Python GUI toolkits...

2011-07-20 Thread rantingrick

RE: *Tim Chase changes topic and talks smack*

On Jul 20, 8:38 pm, Tim Chase  wrote:
> On 07/20/2011 08:17 PM, rantingrick wrote:
>
> > RE: *Ben Finney changes thread subject*
>
> > Please everyone, do not change the subject of someone's thread because
> > it's considered rude. Thank you.
>
> Right...do not change the subject because it's considered rude.
> Change it because the topic drifted from the original topic and a
> fitting subject line helps people decide whether they want to
> read any subsequent sub-threads.  That's just email etiquette as
> old as the tubes.

What about the etiquette of staying on topic? The only person who is
OFFICIALLY allowed to change the subject matter of a thread is the OP.
Sure some folks might make an off topic post here and there however i
find it bombastically rude when folks just change a topic of thread
they do not own.

How would you like it if i came to your house and wrote my name on
your refrigerator door, or used your toilet without asking, or slept
in your bed? I would not do that because i have manners. Feel free to
make yourself comfortable but don't put you feet on the coffee table.
-- 
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  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 "", line 1, in 
zf = zipfile.open(ZIP_PATH)
AttributeError: 'module' object has no attribute 'open'
>>> tf = tarfile.open(TAR_PATH)
>>> tf

>>> tf.close()
>>> tf


*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 "", line 1, in 
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

>>> tf.fp
Traceback (most recent call last):
  File "", line 1, in 
tf.fp
AttributeError: 'TarFile' object has no attribute 'fp'
>>> tf

>>> tf.close()
>>> tf

>>> tf.fileobj

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

>>> f.close()
>>> f


--
2. Zipfile SPECIFIC entry exit
--
>>> zf

>>> zf.fp
>>> zf = zipfile.ZipFile(ZIP_PATH)
>>> zf

>>> zf.fp

>>> zf.close()
>>> zf

>>> 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 "", line 1, in 
zf = zipfile.open(ZIP_PATH)
AttributeError: 'module' object has no attribute 'open'
>>> tf = tarfile.open(TAR_PATH)
>>> tf

>>> tf.close()
>>> tf


*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 "", line 1, in 
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

>>> tf.fp
Traceback (most recent call last):
  File "", line 1, in 
tf.fp
AttributeError: 'TarFile' object has no attribute 'fp'
>>> tf

>>> tf.close()
>>> tf

>>> tf.fileobj

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

>>> f.close()
>>> f


--
2. Zipfile SPECIFIC entry exit
--
>>> zf

>>> zf.fp
>>> zf = zipfile.ZipFile(ZIP_PATH)
>>> zf

>>> zf.fp

>>> zf.close()
>>> zf

>>> 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 "", line 1, in 
zf = zipfile.open(ZIP_PATH)
AttributeError: 'module' object has no attribute 'open'
>>> tf = tarfile.open(TAR_PATH)
>>> tf

>>> tf.close()
>>> tf


*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 "", line 1, in 
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

>>> tf.fp
Traceback (most recent call last):
  File "", line 1, in 
tf.fp
AttributeError: 'TarFile' object has no attribute 'fp'
>>> tf

>>> tf.close()
>>> tf

>>> tf.fileobj

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

>>> f.close()
>>> f


--
2. Zipfile SPECIFIC entry exit
--
>>> zf

>>> zf.fp
>>> zf = zipfile.ZipFile(ZIP_PATH)
>>> zf

>>> zf.fp

>>> zf.close()
>>> zf

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


Re: Inconsistencies between zipfile and tarfile APIs

2011-07-21 Thread rantingrick
On Jul 21, 11:13 pm, Corey Richardson  wrote:
> Excerpts from rantingrick's message of Thu Jul 21 23:46:05 -0400 2011:
>
> > 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.
>
> I agree, actually.

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

PTB: "Sorry we cannot break backwards compatibility"
Rick: But what about Python 3000?
PTB: " Oh, well, umm, lets see. Well that was then and this is now!

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.

>>> from archive import ZipFile, TarFile
>>> zf = ZipFile(path, *args)
>>> tf = TarFile(path, *args)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inconsistencies between zipfile and tarfile APIs

2011-07-21 Thread rantingrick
On Jul 22, 12:05 am, Corey Richardson  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-21 Thread rantingrick
On Jul 22, 12:45 am, Terry Reedy  wrote:
> On 7/22/2011 12:48 AM, rantingrick wrote:
> > On Jul 21, 11:13 pm, Corey Richardson  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"

Re: Inconsistencies between zipfile and tarfile APIs

2011-07-22 Thread rantingrick
On Jul 22, 3:26 am, Lars Gustäbel  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 "", line 1, in 
 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
 

> > 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  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, "[email protected]"
 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  wrote:
> Frank Millman  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  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  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  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: Convert '165.0' to int

2011-07-23 Thread rantingrick

On Jul 23, 1:53 am, Frank Millman  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  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  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: Validating Entry in tkinter

2011-07-24 Thread rantingrick
On Jul 24, 7:11 pm, Saul Spatz  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


  1   2   3   4   5   6   7   8   >