PyWart: Packages (oh how thou art lacking!)

2013-11-10 Thread Rick Johnson


 The Pros of Python Packages:


  Python packages require no special syntax to declare which
  modules are members of the package. Instead, Python simply
  allows the programmer to utilize the hierarchy of his file
  system to decide *which* modules are in *which* packages.

  Sure you've got to create a __init__.py file under the
  directory which will become the package, which is just one
  operation to preform, as opposed to writing uses package
  blah in every damn source file!

  But the real genius is in the consistency!

  By utilizing such a novel approach to packaging, the
  implementation of Python packages remains consistent with
  Python modules. Let's face it people, packaging by any
  other means is just re-inventing the wheel!


 The Cons of Python Packages:


  1. No ability to EASILY share state between package
  members. Sure you can import and inject symbols until
  you're fingers bleed, but all you've done is create an
  unmaintainable spaghetti mess!

  2. Attempting to use packages to create a hierarchy of
  library modules is even more difficult and opens a
  Pandora's box of confusion, circular imports, name errors,
  unintended side effects, etc, etc...


 What should a package be anyway?


  Whilst python packages can be useful, their design is so
  woefully inadequate as to render them almost useless. To
  describe the disparities using an example:

Imagine if classes were nothing more than an
encapsulation of N functions that share information via
a global variable self -- no inheritance, no
polymorphism, no overloading, no blah blah blah...

  Sure, i could find a use for such a type, but the usage
  would be painfully limited.

  So now we find ourselves faced with the reality of the
  glaring question -- What the hell should a python package
  be exactly?

  A package SHOULD be an extrapolation of the namespace
  methodology, in the purest form. You start with local
  scope, then you proceed to module level scope, then
  package level scope (well, that's my wish anyway!), and
  finally, global scope[*]

  Just as class members can share information easily via
  self, package members should have this ability also.


 Some food for thought...


  Namespaces are one honking great idea -- let's do more of
  those!


 REFERENCES:

  [*] Even though Python does not officially support
  global variables, you can emulate such functionality by
  injecting objects into __builtins__, since __builtins__ is
  available in every module namespace.
-- 
https://mail.python.org/mailman/listinfo/python-list


PyWart: Python modules are not so modular after all!

2013-11-10 Thread Rick Johnson


 The Pros of Python Modules:


  Python modules require no special syntax to create, nor do
  they induce extra indentation in your source code to
  maintain readability. Simply write some Python code in an
  editor, save it with a py|pyw extension, throw in a
  directory that python can find, and WHAMO, you've got
  yourself an importable module namespace!

  Of all the package implementations i've seen, Python's use
  of the source file as a module is absolutely my favorite

  But don't pucker up your benevolent anus just yet!


 The Cons of Python Modules:


  1. Modules cannot be extended or manipulated by the
  programmer. Basically the PyGods have handed us modules,
  but they failed to give us any tools to manipulate them --
  heck, they might as well have blessed us an unlimited
  supply of high carbon steel but cursed us with an
  atmosphere that does not support combustion.

  What good is ANY namespace when you cannot override it's
  fundamental interface? And interfaces are the key to OOP!

  Is __setattr__/__getattr__ ringing a bell people?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: New user's initial thoughts / criticisms of Python

2013-11-10 Thread Rick Johnson
On Saturday, November 9, 2013 10:30:26 AM UTC-6, rusi wrote:
 [...]
 Well

 print ( {mon:mondays suck,
  tue:at least it's not monday,
  wed:humpday
 }.get(day_of_week,its some other day)
   )
 may be dense
 Separate into named dictionary and its ok (I think!)

Proper code formatting can do WONDERS for readability!

## START CODE ##
d = {
mon:mondays suck,
tue:at least it's not monday,
wed:humpday
}
default = some other day
target = tue
print d.get(target, default)
target = blah
print d.get(target, default)
## END CODE ##

Of course you could create something reusable and interface-ee.

## START CODE ##
class UsageError(Exception):
pass

class Case(object):
def __init__(self, defaultDict=None, defaultValue=None):
self.d = defaultDict or {}
self.defaultValue = defaultValue

def __str__(self):
return Case({0}).format(self.d)

def __call__(self, key):
try:
v = self.d[key]
except KeyError:
v = self.defaultValue
return v

def __getitem__(self, k):
raise UsageError(RTFS MAN!!!)

if __name__ == '__main__':
import calendar
d = {
mon:mondays suck,
tue:at least it's not monday,
wed:humpday
}
case = Case(d, some other day)
try:
case[tue]
except UsageError:
print 'Stopped improper useage.'
print case
lst = [s.lower() for s in calendar.weekheader(3).split(' ')]
for dayName in lst:
print Case.__call__({0!r}) - {1!r}.format(dayName, case(dayName))
## END CODE ##

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


Re: The narcissism of small code differences

2013-11-10 Thread Rick Johnson
On Saturday, November 9, 2013 6:42:04 AM UTC-6, Steven
D'Aprano wrote: 
 Uses an example written in Ruby, but don't
 let that put you off:

Why would it? I write Ruby code all the time. Ruby code in
and of itself does not bother me, what bothers me about Ruby
is the ease at which a programmer can write inconsistent and
convoluted code -- evidenced by the poor examples in your
linked article. Case in point.

To save anyone else from reading this long-winded blab
fest chalk full the driest humor and cyclic illogical
meandering that could make a ferris-wheel blush with
jealousy...

  In a nutshell the author attempts to plead for the
  longevity of old code bases simply on the basis of his
  assertion that old code bases are less buggy and
  contain more wisdom than their new brethren -- both of
  which are absurd conclusions!
  
Now, whilst he is correct regarding the narcissism of
programmers (i must admit we are all guilty of this deadly
sin), his attempts to draw parallels between Freudian
pathologies and software development idiosyncrasies is,
in fact, the very HEIGHT of sophistry!

Has the author considered that new functionality often
renders old code bases useless, or at the very least,
antiquated? Even code bases that are in fact bug free (for
*some* definition of bug free!)

Has the author consider that changes in external
dependencies can render a code base useless? Py3000 ring
a bell folks?

Is the author also unaware of evolution? 

Doth he falsely believe that even the BEST programmer can
look back on code he wrote a few years ago and not think of
some way it could be improved? GvR had such a realization
not so long ago -- and then there was Py3000!!!

From something as simple as code restructuring for
readabilities sake; to choosing better naming conventions;
to improving consistency; reformulating algorithms to
eliminate bottlenecks; taking advantage of new functionality
in external libraries; or implementing new design patterns,
and on and on -- the list is limitless man!

The fact is, no code base will ever be perfect. Code will
constantly need updating and upgrading. The challenge is to
remove the old crusty bits and inject consistency everywhere
we can. That's not narcissism, that's altruism.








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


Re: Creating a function for a directory

2013-11-11 Thread Rick Johnson
On Monday, November 11, 2013 4:26:46 PM UTC-6, Matt wrote:

 So I want to take the file, desktop/test.txt and write
 it to desktop/newfolder/test.txt. I tried the below
 script, and it gave me: IOError: [Errno 2] No such file
 or directory: 'desktop/%s.txt'. Any suggestions would be
 great.

 def firstdev(file):
   in_file = open(desktop/%s.txt) % file
   indata = in_file.read()
   out_file = open(desktop/newfolder/%s.txt, 'w') % file
   out_file.write(indata)
   out_file.close()
   in_file.close()
 firstdev(test)

1. i believe win32 file paths require a qualifying volume
letter.

2. Never, ever, *EVER* write data to disc before confirming
the paths your passing are pointing to the location you
intended to write the data. Use os.path.exists(path) to test
your paths BEFORE trying to write data.

3. Be sure your variables names are both self documenting
and non clobbering. psst: file is a builtin! Using
filename would be a far wiser choice for a variable
containing a filename. When i see file, i think of a file
object

4. When dealing with files you must be sure that exceptions
are handled cleanly. You don't want open file objects
floating aimlessly around in memory because your naive code
blew chunks.

5. Remember, you cannot write a file into a directory that
does not exist.

6 For OS compatibility always use os.path.join() to join
path parts into a whole. This method will insert the proper
separator for you depending on the OS.

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


Re: PyWart: Python modules are not so modular after all!

2013-11-11 Thread Rick Johnson
On Monday, November 11, 2013 1:34:54 AM UTC-6, Steven D'Aprano wrote:
 import sys
 sys.modules[mymodule] = any_object_you_like()

Thanks for this great advice!

I'm not particularly fond of injecting names and objects in
this manner due to the surprise factor, especially when
the names are going to be global, but i'm going to do it
anyway since python gives me no other choice!

*evil-grin*

However, there is no reason why good cannot prevail over
evil. By utilizing an intelligent design, logical
hierarchy, and most importantly: quality documentation and
commenting to shine a light on such dark and mystical
practices, i can elevate a kludge into the realms of
elegance.

Stay tuned for a future thread discussion on the topic...
-- 
https://mail.python.org/mailman/listinfo/python-list


PyMyth: Global variables are evil... WRONG!

2013-11-11 Thread Rick Johnson
PyMyth: Global variables are evil... WRONG!


 Python's Global Hysteria:

How many times have your heard or read the phrase: Global
variables are evil? Well if you've been a member of the
Python community, I'll bet you've heard or read it more than
most other community members.

In this thread, i want to get to the bottom of this whole
global-phobia thing once and for all, and hopefully help
you folks understand that globals are not all that bad --
when DESIGNED and USED correctly that is!


 The denial of the 99%:

Python has globals, but we just can't admit it!

The creators thought they would prevent the little
PyPeople from hurting themselves by handicapping our
globals in the form of module level globals.

But even the module level globals can be accessed
globally if the module they are contained in is imported
everywhere.

import glomod
glomod.var # Access
global.var = newValue

Which leads me to the conclusion that the designers were
either naive or underestimated the chutzpah of this fine
community.


 The Power of the 1%:

Most of this fear of globals can be traced back to a
minority of naive coders who used globals haphazardly and
were hurt by them, sarcasmand now we ALL have to suffer
because future idiots need to be protected from themselves!
/sarcasm

Too many times I've seen idiotic uses for globals.

One more atrocious example was dialog return values stored
as globals so the dumb coder could eaisly restore the
previous state of the dialog values between successive
calls.

Obviously the best solution would be for the dialog object
ITSELF to store (and restore) the values when necessary, but
alas, here i am again expecting people to create interfaces
that are consistent and logical. *rolls-eyes*

Of course we can only blame the dialog designer and not the
caller for this design flaw, but the caller still has no
excuse for globally storaging these values.

If the caller cannot repair the mistake by extending the
dialog object himself, then he can store the values within
the current module or class level scope. There is no excuse
for elevating this information to global scope.

However, there ARE justified uses of global variables!


 Justifying Global Variables:

Globals are justified when they are used to communicate
information between scopes that otherwise were meant to be
mutually exclusive. One good example would be package sub-
modules.

Now. Some might believe that the purity of namespaces
becomes tainted if they can be violently penetrated by
global variables. But again, they are falling back on gut
reactions fostered from years of brain washing. Yes, globals
can be bad (if misused), but for the most part they are
crucial to transferring information CLEANLY between isolated
namespaces

But even globals themselves are not good enough UNLESS we
engineer a global hierarchy!


 From Flat to Nested == From Tricked to Bested:

One of the shortcomings of the current implementation of
global variables is their inherent flat access nature.
There is no hierarchy of globals, and once all the good
names are taken, your screwed!

 But Rick, even when we use globals, we don't need that many

Only if you consider the single package that represents your
program, but what about the thousands of support libraries
with millions of lines of code that work in the background
to make your measly few thousand lines of code work?  What
about all the globals that they have injected?

 Never thought of that really

Throwing out global names UNADORNED is folly. Could you
imagine telephone numbers without area codes?

 Hmm: Am i calling Jim in Beverly Hills California???

   california.beverlyhills.jim

 or Jim in Spokane Washington???

   washington.spokane.jim

You see, you need to QUALIFY these names not only to make
then unique, but also so the caller will understand who he
is calling.

Same goes for globals.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyMyth: Global variables are evil... WRONG!

2013-11-11 Thread Rick Johnson
On Monday, November 11, 2013 8:47:09 PM UTC-6, Tim Daneliuk wrote:
 I think this is certainly the use case most people would
 suggest. But I think you may have missed the real reason
 most modern designers object to inter-module globals:  The
 presence of such entities almost always means the code has
 been designed badly.  Whether we're writing pristine OO
 code (cough, cough) or more traditional procedural stuff,
 information hiding is a good thing.

Yes, and i agree. But you cannot hide everything. There
will always be a need to share information.

 When and where there is a need for modules (or programs,
 or machines, or clouds, or interstellar space ...) to
 share information, my view is this is better done via some
 sort of interface/message passing mechanism.

But python modules can't be interfaces because interfaces
should protect internal data, prevent external forces from
meddling with internal state (EXCEPT via the rules of a
predefined contract), hide dirty details from the caller,
and have clearly defined access points.

  BUT PYTHON MODULES DON'T FOLLOW THIS DESIGN PATTERN!

No, Python modules can be poked, prodded, and violated by
any pervert who can spell the word import.

Attribute values can be reassigned and state can be
externally manipulated resulting in all types of undefined
behaviors -- that does not sound like an interface to me.

So if python modules are importable everywhere, and mutable
from everywhere, then python modules are merely addresses to
a collection of global variables? And they're only
interfaces superficially?

So that leaves us with Python's current implementation of
unofficial global variables implemented as puesdo-
interfaces by module objects that are victims waiting to be
violated.

Interesting.

  IF IT WALKS LIKE A GLOBAL DUCK AND...
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Creating a function for a directory

2013-11-11 Thread Rick Johnson
On Monday, November 11, 2013 5:11:52 PM UTC-6, Chris Angelico wrote:
 On Tue, Nov 12, 2013 at 9:51 AM, Rick Johnson
  1. i believe win32 file paths require a qualifying volume
  letter.
 They do not; omitting the drive letter makes the path relative to the
 current drive (and since it doesn't start with a directory specifier,
 the current directory).

Hmm. Let's confirm:

 import os
 os.path.exists(C:/Windows/System32)
True
 os.path.exists(/Windows/System32)
True

Yep, it's official. Implicit File Path Resolution
I need to author a PyWart on this soon!

  2. Never, ever, *EVER* write data to disc before confirming
  the paths your passing are pointing to the location you
  intended to write the data. Use os.path.exists(path) to test
  your paths BEFORE trying to write data.
 Why? Why, oh why? If there's a problem, it'll be signalled
 with an exception.

Except when there's a problem that won't be signaled by an
EXCEPTION, but will be signaled by EMOTIONS; like for
instance removing the wrong directory or truncating the
wrong file because of a typo in your source code.

 OPPS! :-'(

 Testing that the path exists opens you up to race
 problems, so you won't see anything now, but some day your
 code will be in a concurrent situation and you'll get
 unexpected exceptions. Why not just expect the exception?

Because today i'm not facing a concurrent situation, so i'm
not going to bother and protect from it. Just like i'm not
facing a snake bite, so i won't bother to lug around a vial
of antidote. Your attempts to discredit me via hypothetical
scenarios is entertaining however.

 This one's arguable. How often do you use the 'file'
 builtin? I've worked with files in Python innumerable
 times, and I don't remember the last time I used 'file'.
 Yes, avoid shadowing important builtins like 'list' and
 'int', but 'id' and 'file' aren't that big a deal.

My first concern is with the OP adopting self documenting
names. Shadowing file is merely ensuring that the OP knows
file is a builtin. Shadowing any builtin can create very
difficult bugs to track. This is the point the OP should
remember.

 They won't float around forever. The garbage collector
 will get to them.

That depends on how they are stored. You make too many
assumptions Chris. I don't have an problems with GC's, but
i'm not about to write sloppy code and assume the GC is
going to swoop in and save me like a feline trapped in a 
tree.

  5. Remember, you cannot write a file into a directory that
  does not exist.
 So? Exception thrown, traceback printed to console,
 process terminated cleanly. I'm not seeing a problem here.

Now you're just trolling!

def firstdev(file):
in_file = open(desktop/%s.txt) % file
indata = in_file.read()
out_file = open(desktop/newfolder/%s.txt, 'w') % file

Just from reading that code NO ONE could know for sure if
newfolder even existed BEFORE the OP tried to open the
out_file. Maybe the OP thinks that missing sub-directories
are auto-created by the open function, but there's no way to
know for sure, hence my comment.

  6 For OS compatibility always use os.path.join() to join
  path parts into a whole. This method will insert the proper
  separator for you depending on the OS.
 Technically true. However, most modern OSes will accept a
 slash. There'll be a few situations where that's not true,
 but the OP an happily just use slashes for simplicity.

Many a developer have lived to regret those words.

PS: I thought Steven was the official devils advocate
around here? Hmm. I guess everyone needs a day off.

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


Re: PyMyth: Global variables are evil... WRONG!

2013-11-12 Thread Rick Johnson
On Tuesday, November 12, 2013 8:12:10 AM UTC-6, jongiddy wrote:

 Can you please give an example where having a module
 provide a global variable would work better than any of:
 [snip]

Well my point is that the attributes of any Python module
are emulating globals already. The fact that we have to
mutate them via a psuedo interface makes us falsely
believe we are using an interface -- but we aren't!

 PYTHON MADE ACCESSING GLOBAL VARIABLES MORE DIFFICULT!

As example. I could import the math module and start
fiddling with attributes. Let's say for example i can change
the value of math.pi. Most people would probably say what's
the problem with that?, here, let me show you.

# mod1.py
print mod1.py
import math
math.pi = tasty

# mod2.py
print mod2.py
import math
print ' value of math.pi is:', math.pi
radius = 10
math.pi * radius

#modmain.py
import mod1
import mod2
print dir(mod1)
print dir(mod2)

When you run modmain.py you will see that not only have we
changed the global variable pi to a string, but thanks to
a dumb overloading of the multiply operator, python will
happily give use the wrong answer -- but that's another
problem, let's stay focused on the global problem for now!

When i type math.pi, i feel as though i'm accessing an
interface, BUT I'M NOT! If i was indeed accessing a TRUE
interface, the interface would have thrown a Type error for
attempting to assign a value of type string to what should
only be a float. The interface would have protected it's
internal data from corruption, but it didn't.

  BECAUSE IT'S NOT AN INTERFACE!

It's just a dumb namespace with no exposed hooks to control
it's underlying behavior.

  MY POINT IS:

Python designers act like globals are SO evil, but then they
give us modules which are containers for global variables,
and now the globals contained within those modules are
wolves in sheep's clothing. Are they just trying to fool
themselves, or fool us?

  FOOD FOR THOUGHT:

What's worse? A wolf? Or a wolf in sheep's clothing?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyMyth: Global variables are evil... WRONG!

2013-11-12 Thread Rick Johnson
On Tuesday, November 12, 2013 9:33:50 AM UTC-6, jongiddy wrote:
 I'm not sure where you get the feeling you're accessing an
 interface.

Because the constant PI should never change. Sure we can
argue about granularity of PI, but that argument has no
weight on the fact that PI should be a constant.

By placing PI in the module math, we are creating a pseudo
interface. We (the creators) are assuming that PI will be a
constant and never change, and the caller is assuming that
pi will remain static,  but not only can it be mutated, it
can be mutated globally.

math.pi is neither a constant nor a local module attribute,
math.pi is really a global variable. This is true not only
for math.pi, but ALL attributes of ALL python modules.

 If I typed this, I would feel like I was trying
 to change a fundamental constant. You have just
 demonstrated that going into other modules and changing
 their attributes (whether they are variables, functions or
 classes) is generally a BAD idea, and I don't think I've
 ever seen anyone recommend doing this, except possibly as
 a workaround or for debugging purposes. On the other hand,
 you initially suggested that modifying globals contained
 within namespaces (i.e. modules) is a good way to
 communicate between modules.

You missed my point: only IF python modules were TRUE
interfaces. It's not a good idea under python's current
implementation of modules. My thread is intended to
underscore this very design flaw.

 This inconsistency

There is no inconsistency in my logic, quite the contrary.

I think you're having difficulty following along because
you've been brainwashed by Python for too long. You've
falsely believed that Python does not have globals, but
it does! You just have to mutate then via a pseudo
interface.

 is why I was asking for a good example (i.e.
 a realistic example where the use of global variables
 provides the best solution).

I gave a good example in my very first post:

RR: Globals are justified when they are used to
[share] information between scopes that otherwise
were meant to be mutually exclusive. One good
example would be package sub-modules.

 Just because a tool allows you to do something does not
 make it a good idea. Try this paraphrase of your last
 post: Ladder designers act like standing on the top rung
 is SO evil, but then they give us ladders with a top rung,
 Are they just trying to fool themselves, or fool us?

EXACTLY. And whilst your comparison is both intelligent and
funny, you're just re-iterating my point!

We have all been brainwashed by authorities. First they
give us rules, then they give us the power to break
those rules. If standing on the top rung is SO
dangerous, then don't manufacture your ladders with top
rungs. Else, shut up about it!

  THOU SHALT NOT KILL

Well i can't live WITH the B!@$%!!!

  THOU SHALT NOT COMMIT ADULTERY

Then why create me with a unquenchable desire for sex?

  THOU SHALT NOT TAKE THE LORDS NAME IN VAIN

GOD DAMMIT! Stop making all these opposing rules.

So the designers detest globals huh? But python module
attributes are really global because they can be accessed
and mutated ANYWHERE!. This enigma leads to two logical
design philosophies: (anything else is folly)

   1. Accept that globals are useful, and make them
  available through a real global syntax, not
  some attribute of a module that appears to be
  local, but in reality is global. Then prevent
  external mutation of module attributes directly,
  and instead, require that mutation must follow a
  contract defined by internal module setter
  functions.

   2. Remain convinced that global mutation is evil
  and prevent mutation of all python module
  attributes. You can import modules, but you can't
  mutate their contents.

THIS IS HOW YOU DESIGN FOR CONSISTENCY, NOT HYPOCRISY!

@LanguageDesigners: But whatever you do, don't hide globals
behind pseudo interfaces, because then you have created
something worse than a global; you've created a global in
sheep's clothing. And you're a hypocrite.


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


Re: PyMyth: Global variables are evil... WRONG!

2013-11-12 Thread Rick Johnson
On Tuesday, November 12, 2013 11:00:37 AM UTC-6, Rick Johnson wrote:
[snip]
 We have all been brainwashed by authorities. First they
 give us rules, then they give us the power to break
 those rules. 

The devil himself said it best:

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

Hmm. How do we humans cope with all these opposing rules? If
we created an AI with all the ridiculous, convoluted and
opposing rules that we humans live with on a daily basis, it
would blow chunks.

How do our minds possibly cope with such illogical rules
without blowing chunks?

We cope by re-inventing reality.  We cope by convincing
ourselves that truths are not true and lies are true.

We cope by designing languages that obfuscate globals behind
pseudo interfaces so we can get farm fuzzy feelings in our
tummy, then we can secretly break the rule when non-one is
looking.

By doing this we convince ourselves that we are pure.

HUMANS: What a pathetic bunch of slaves!

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


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


PyModule(G.py): Now Python has REAL globals -- and their scoped to boot!

2013-11-12 Thread Rick Johnson

# Copyright 2013, Rick rantingrick Johnson
#
# Permission to use, copy, modify, and distribute this software for 
# any purpose and without fee is hereby granted, provided that the above
# copyright notice appear in all copies.
#
# THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
#-
# 
# This script needs to be loaded when Python starts. But since i'm
# not supplying an installer, you'll have to tell Python how to load 
# it yourself. Which is not very difficult really.
#
# The easiest method to auto-load this script is to create a .pth
# file and save it somewhere that python can find it. If your a noob
# and don't know what that means, then just throw the .pth file in
# your PythonXY folder. 
#
# The contents of the .pth file MUST include the following line:
# 
# import G
#
# Noob Note: You can name the .pth file anything you want, but this
# module must be named G.py. Yes, with a capital G!
#
# Enjoy.

import sys as _sys

class _Globals(object):

DESIGN NOTES:
This object is meant to provide a namespace for true global
variables in Python -- with no need to import anything. 

A toplevel Globals object is injected at runtime, and always 
available within ANY Python module via the name G. Note the
capital letter, it's significant! 

I like global variables to be qualified, but not behind a
long name, and only a single letter can fulfill both.

And since globals is already a built-in function, G is the
next best thing.

I also wanted global access to be noticeable in the source,
but not overwhelming!!! Hence the  choice of capital G over
lowercase g.

Those of you with  Java background should be comfortable
with G due to your experiences with the R object.

PUBLIC METHODS:
add_space(str name)
get_path()

USAGE:
Assignment:
G.name = value
Query:
G.name
Expansion:
G.add_namespace(name)


MUTATE_MSG = WARNING: The value of global variable {0!r} has changed!
DELETE_MSG = 'WARNING: The global variable {0!r} was deleted!'
ACCESS_MSG = 'Access to private variable {0!r} is denied!'

def __init__(self, name):
self.__dict__[__private] = {
dirlst:[],
name:name,
}

def __str__(self):
fmtstr1 = {0}(\n{1}\n)
fmtstr2 = {0}(empty)
lst = []
pDict = self.__dict__[__private]
for name in pDict[dirlst]:
value = self.__dict__[name]
lst.append( {0} = {1!r}.format(name, value))
values = '\n'.join(lst)
if not values:
fmtstr1 = fmtstr2
return fmtstr1.format(pDict[name], values)

def __dir__(self):
return self.__dict__[__private][dirlst]

def __getattribute__(self, name):
##print _Globals.__getattribute__({0!r}).format(name)
if name == __private :
# This only stops direct access!
raise Exception(self.ACCESS_MSG.format(self.__dict__[__private]))
return object.__getattribute__(self, name)

def __setattr__(self, name, value):
##print _Globals.__setattr__({0!r}, {1!r}).format(name, value)
if name in self.__dict__:
pDict = self.__dict__[__private]
path = {0}.{1}.format(pDict[name], name)
if name == __private:
# This only stops direct access!
raise Exception(self.ACCESS_MSG.format(name))
else:
print self.MUTATE_MSG.format(path)
else:
self.__dict__[__private][dirlst].append(name) 
self.__dict__[name] = value

def __delattr__(self, name):
##print _Globals.__delattr__({0!r}).format(name)
pDict = self.__dict__[__private]
path = {0}.{1}.format(pDict[name], name)
if name == __private:
raise Exception(self.ACCESS_MSG.format(path)) 
elif name in self.__dict__:
print self.DELETE_MSG.format(path)
del self.__dict__[name]
pDict[dirlst].remove(name)

def get_path(self):
return self.__dict__[__private][name]

def add_namespace(self, name):
Add a new global namespace named name
pDict = self.__dict__[__private]
pDict[dirlst].append(name)
newname = pDict[name] + .{0}.format(name)
self.__dict__[name] = _Globals(newname)

#
# Inject a toplevel instance of _Globals (named G) into the
# builtins module namespace.
_sys.modules['__builtin__'].__dict__['G'] = _Globals(G)

if __name__ == '__main__':
print G
print '\nAdding globals to G'
G.str = 

Re: PyMyth: Global variables are evil... WRONG!

2013-11-12 Thread Rick Johnson
On Tuesday, November 12, 2013 4:41:34 PM UTC-6, jongiddy wrote:
 On Tuesday, November 12, 2013 5:00:37 PM UTC, Rick Johnson wrote: 
 1. Accept that globals are useful, and make them
available through a real global syntax, not
some attribute of a module that appears to be
local, but in reality is global. Then prevent
external mutation of module attributes directly,
and instead, require that mutation must follow a
contract defined by internal module setter
functions.
 2. Remain convinced that global mutation is evil
and prevent mutation of all python module
attributes. You can import modules, but you can't
mutate their contents.
 From your first post, I take it you're not keen on option #2.

That is correct, i prefer to use REAL interfaces.

 For #1, module globals are exactly the hierarchically
 namespaced globals that you desire in your first post,

Agreed.

 except they are variables, not get/set handlers (which is
 what I take you to mean by an interface). 

Yes, python modules expose ALL members publicly and have no
support for contractual interfacing.

 Why not create a PEP to provide handlers for module
 attributes? You could base it on PEP 213, which describes
 the same feature for classes. 

I would love to see modules expand to something more than
mere boxes to stuff variables. But then again, modules
are not going to provide the ease of access that globals
demand due to the import problem.

Modules will not be a good place to store globals because
modules must be imported and globals should never need
importing. 

I've just released a module on Python-list called G.py
that does exactly what i propose. It's not perfect, but i
think you'll understand what i'm proposing after testing 
it.

 As a bonus, this would trivially support option #2 (e.g.
 non-mutable math.pi) by raising an exception for the set
 operator.

math.pi should be math.PI. and PI should be a CONSTANT. 
And not just a pseudo constant, but a REAL constant that 
cannot be changed.
-- 
https://mail.python.org/mailman/listinfo/python-list


PyModule(C.py): Now Python has REAL constants -- and they're scoped to boot!

2013-11-12 Thread Rick Johnson

# Copyright 2013, Rick rantingrick Johnson
#
# Permission to use, copy, modify, and distribute this software for
# any purpose and without fee is hereby granted, provided that the above
# copyright notice appear in all copies.
#
# THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
#-
#
# This script needs to be loaded when Python starts. But since i'm
# not supplying an installer, you'll have to tell Python how to load
# it yourself. Which is not very difficult really.
#
# The easiest method to auto-load this script is to create a .pth
# file and save it somewhere that python can find it. If your a noob
# and don't know what that means, then just throw the .pth file in
# your PythonXY folder.
#
# The contents of the .pth file MUST include the following line:
#
# import C
#
# Noob Note: You can name the .pth file anything you want, but this
# module must be named C.py. Yes, with a capital C!
#
# Enjoy.

import sys as _sys


class ConstantDeletionError(Exception):
pass
class ConstantSyntaxError(Exception):
pass
class ConstantMutationError(Exception):
pass


class _Constants(object):

DESIGN NOTES:
This object is meant to provide a namespace for true constant
variables in Python -- with no need to import anything!

A toplevel constants object is injected at runtime, and always
available within ANY Python module via the name C. Note the
capital letter, it's significant!

I like constant variables to be qualified, but not behind a
long name, and only a single letter can fulfill both wishes.

I also wanted constants access to be noticeable in the source,
but not overwhelming! Hence the  choice of capital C over
lowercase c.

Those of you withJava background should be comfortable
with C due to your experiences with the R object.

PUBLIC METHODS:
add_namespace(str name)
get_path()

USAGE:
Assignment:
C.name = value
Query:
C.name
Expansion:
C.add_namespace(name)

MUTATE_MSG = Constants cannot be mutated once intitalized!
DELETE_MSG = 'WARNING: The constant variable {0!r} was deleted!'
ACCESS_MSG = 'Access to private variable {0!r} is denied!'

def __init__(self, name):
self.__dict__[__private] = {
dirlst:[],
name:name,
}

def __str__(self):
fmtstr1 = {0}(\n{1}\n)
fmtstr2 = {0}(empty)
lst = []
pDict = self.__dict__[__private]
for name in pDict[dirlst]:
value = self.__dict__[name]
lst.append( {0} = {1!r}.format(name, value))
values = '\n'.join(lst)
if not values:
fmtstr1 = fmtstr2
return fmtstr1.format(pDict[name], values)

def __dir__(self):
return self.__dict__[__private][dirlst]

def __getattribute__(self, name):
##print _Constants.__getattribute__({0!r}).format(name)
if name == __private :
# This only stops direct access!
raise Exception(self.ACCESS_MSG.format(name))
return object.__getattribute__(self, name)

def __setattr__(self, name, value):
##print _Constants.__setattr__({0!r}, {1!r}).format(name, value)
if name in self.__dict__ and  name != __private:
# This only stops direct access!
raise ConstantMutationError(self.MUTATE_MSG.format(name))
else:
self.__dict__[__private][dirlst].append(name.upper())
self.__dict__[name.upper()] = value

def __delattr__(self, name):
##print _Constants.__delattr__({0!r}).format(name)
pDict = self.__dict__[__private]
path = {0}.{1}.format(pDict[name], name)
if name == __private:
raise Exception(self.ACCESS_MSG.format(path))
elif name in self.__dict__:
raise ConstantDeletionError()

def get_path(self):
return self.__dict__[__private][name]

def add_namespace(self, name):
Add a new constants namespace named name
name = name.upper()
pDict = self.__dict__[__private]
pDict[dirlst].append(name)
newname = pDict[name] + .{0}.format(name)
self.__dict__[name] = _Constants(newname)

#
# Inject a toplevel instance of _Constants (named C) into the
# builtins module namespace.
_sys.modules['__builtin__'].__dict__['C'] = _Constants(C)

if __name__ == '__main__':
print C
print '\nAdding constants to C'
C.str = 
C.int = 1
C.float = 1.333
print C
print '\nMutating constants of C'
try:
C.STR = XXX
except ConstantMutationError:
pass
try:
C.INT = 10
except ConstantMutationError:
 

Re: [Help] [Newbie] Require help migrating from Perl to Python 2.7 (namespaces)

2012-12-25 Thread Rick Johnson
On Tuesday, December 25, 2012 11:10:49 AM UTC-6, Dave Angel wrote:

 We all make mistakes, like my referring to class methods when I
 meant instance methods. 

This mistake reminded of how people in this group (maybe not you in particular) 
happily accept the terms instance method and class method HOWEVER if you 
_dare_ use the terms instance variable or class variable you get a swift 
rebuke. 

Would anyone care for another serving of logically inconsistent py? 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Help] [Newbie] Require help migrating from Perl to Python 2.7 (namespaces)

2012-12-25 Thread Rick Johnson
On Tuesday, December 25, 2012 3:08:21 PM UTC-6, Dennis Lee Bieber wrote:
 Only that many of us don't believe Python has /variables/, the use
 of instance/class as a modifier is thereby moot.

What IS a variable Dennis?
#

#Variable (ComputerScience)#

# In computer programming, a variable is a storage #
# location and an associated symbolic name (an identifier) #
# which contains some known or unknown quantity or #
# information, a value. The variable name is the usual way #
# to reference the stored value; this separation of name   #
# and content allows the name to be used independently of  #
# the exact information it represents. [...] The   #
# identifier in computer source code can be bound to a #
# value during run time, and the value of the variable may #
# thus change during the course of program execution.  #

#
With that accurate definition in mind you can now understand how Python classes 
CAN and DO have variables, just as Python modules have variables; psst: they're 
called global variables!

Now, whilst i don't believe we should haphazardly re-define the definition of 
CS terms (or worse, re-invent the wheel by inventing new terms when perfectly 
good terms exist) I DO believe we should interpret these terms in their current 
context.

For instance, Python has no REAL global variables, so we can happily refer to 
module level variables as global variables. However in many other languages 
(like Ruby for instance) we can declare REAL global variables that are known 
across all namespaces. And since Ruby also has modules which /themselves/ can 
contain variables, we would refer to module level variables as module 
variables. 

 An instance method is a method that works on an instance of the
 class, whereas a class method is meant to work on the class as a
 whole

Allow me to use better terms:

  An instance method is a method that is known to an
  instance of the class only, whereas a class method is
  known to all instances and accessible from the class
  identifier

Now with that clear description in mind, apply it to variables:

  An instance method is a method that is known to an
  instance of the class only, whereas a class method is known
  to all instances and accessible from the class identifier.

This transformation is without flaw because it is based on logic and not 
emotion.

 ...I don't know of anyone arguing that Python does not have
 methods.

Of course not because they would have to be insane. However, we should never 
adopt illogical terms just because a few folks cannot resolve the definition of 
the proper terms.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Help] [Newbie] Require help migrating from Perl to Python 2.7 (namespaces)

2012-12-25 Thread Rick Johnson
On Tuesday, December 25, 2012 4:56:44 PM UTC-6, Steven D'Aprano wrote:

 Rick, what makes you think that this is logically inconsistent?
 Method is the accepted name for functions attached to classes. They
 report themselves as methods:
 [...]
 There are two built-ins for creating different types of method: the
 classmethod and staticmethod functions. If you don't think that these
 objects should be called adjective method, then what do you think
 that they should be called?

I'm  not arguing about against instance method/class method name convention, i 
am talking about instance variable/class variable; pay attention!

 On the other hand, the terms instance variable and class variable are
 logically inconsistent with other terminology. It is common practice,
 across dozens or hundreds of languages, to refer to variables by their
 type

Variable have no type, only the value of variable has a type. 

 (either as declared, in static-typed languages like C or Haskell, or
 as they are expected to hold a value in dynamic languages like Ruby and
 Python):

 - an integer variable is a variable used to hold an integer;
 - a string variable is a variable used to hold a string;
 - a float variable is a variable used to hold a float;
 - a boolean variable is be a variable used to hold a boolean;
 - for consistency, a class variable should be a variable used to
   hold a class, e.g.:
   classes = [bool, float, MyClass, Spam, Ham, AnotherClass]
   for cls in classes:  # cls is a class variable
   print The name of the class is, cls.__name__
 - and similarly for consistency an instance variable should be a
   variable holding some arbitrary instance. Since everything in an
   instance in Python, this last one is too general to be useful.

Your last one(sic) comment negates your whole argument of referring to 
variables by what type the variable references. Since EVERYTHING is an obj then 
ALL variables should be termed instance variables (that's going by your logic 
of course).

 Unfortunately people coming to Python from certain other languages,
 particularly Java, (mis)use class variable to mean something completely
 different:

Don't try to confuse us with your illogical ways, Lord Steven. Your sad 
devotion to that ancient hatred of java has not helped you conjure up logical 
terminology, or given you enough clairvoyance to find the truth...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Help] [Newbie] Require help migrating from Perl to Python 2.7 (namespaces)

2012-12-26 Thread Rick Johnson
On Wednesday, December 26, 2012 2:29:13 AM UTC-6, Steven D'Aprano wrote:
 [snip]

I won't reply to your last post on a line-by-line basis because i feel we are 
straying from my general point: which is that we should NEVER re-interpret 
existing words (in an illogical manner) whilst transforming them into specific 
disciplines.

My specific point is that the English word variable is unambiguous and 
transforms smoothly to an abstract idea of an identifier referencing an object, 
and also, that the reference is variable (or has the ability to change). The 
word variable is a WONDERFUL example of transforming existing words into 
specific esoteric disciplines.

Alternatively, you want to argue that the word attribute is a better choice 
NOT because variable cannot transform to a programming context, BUT because 
you want use variable to reference some attribute of an 
object...*smile*..., oh i see.

But seriously, 
What is an attribute anyway?


#Define: Attribute #

# Noun: A quality or feature regarded as a characteristic  #
# or inherent part of someone or something.#


Interesting. And what about inherent?


# Define: Inherent #

# Adjective: Existing in something as a permanent, #
# essential, or characteristic attribute   #


Ahh... so an attribute is attached to an entity (okay, we could easily 
transform the word entity to a memory object, but) ...that is permanent AND 
essential! OPPS! Here is where your logic breaks down. Variables COULD NOT be 
considered permanent: neither existentially or referentially. Please 
re-consider this illogical transformation of the word attribute.

[Slightly Tangential Meanderings Ahead...]
Okay, now that we've ironed-out the wrinkles in our variable and we see how 
variable traverses perfectly into a computing context, i want to talk about 
how some of our most /ingrained/ syntax is NOT correct! Specifically i want to 
talk about class and def.

The words class and def are HORRIBLE choices for defining classes (oops, 
i should say objects, but it seems the brainwashing has run it's coarse!) and 
methods/functions. I know, I know, your gut reaction is to _cling_  to what 
is familiar -- and these words have become FAR TOO familiar to all of us -- but 
again, let's do some introspection of these words we THINK we understand.

Ask yourself. What /is/ a class?

A class is nothing more than a textual template defined by the programmer for 
which Python reads and creates OBJECTS in memory. If instead of class we used 
the word object to define a (wait for it...) object we would NOT ONLY be 
consistent and logical, we would inject more intuitiveness into our language. 
Can you imagine the confusion a new programmer would feel when told that he 
must use classes to create objects when the only definition of classes he 
understands is classrooms and classifications.

So the correct syntax follows:

OBJECT Car(object):
def __init__(self)
#

same goes for methods/functions

FUNCTION foo(args):
... pass

Of course i would be open to obj and func respectively (well maybe). But i 
favor the following syntax for even more intuitive consistency:

define object Car(...):
define function foo(...):

That is a work of logical fine art!. However a new problem arises: function 
an illogical choice. Procedure would be the obvious choice, however, old 
school CS majors YET AGAIN redefined a word into illogic oblivion.

Some people think Python's syntax is great, and i must confess i am one of 
those people, but even after all of Guido's whining about the failures of ABC's 
syntax he then went on to commit the same crimes[1]

[1] to a far less degree of course :-).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Most discussion on comp.lang.python is about developing with Python

2013-11-13 Thread Rick Johnson

Hello Bob,

I understand your concern but you need to realize there is
not much that can (or should) be done *IF* we want to live in
societies that are free from oppression.

The minute we start drawing lines in the sand and punishing
people for exercising their freedom of speech, is when we
start living under Fascism -- and trust me friend;  trolls,
spammers and flamers are nothing compared to overzealous
nanny police forcing other people to live by rules they
refuse to live by themselves. Is Bloomberg ringing a bell[*]

  WHERE DO WE DRAW THE LINE? 

You cannot create social rules in ANY society that do not
infringe upon the personal freedom of others. We ALL have a
right to express ourselves. 

  HOWEVER,

when we live in a free society we must accept that
some people will be annoying; some will be rude; some will
be friendly; some will be hostile; or any number of 
unpleasing emotional states.

Learning to tune out what we find offensive and tune in
what we find pleasing (or interesting) is part of being a
member of any free society.

 SOMETIMES, YOU JUST GOTTA PUT YOUR BIG BOY PANTS ON.

One aspect about online forums (unlike real life) is that
you can avoid people (or opinions) you find offensive simply
by choosing not to read their words.

But, at the end of the day, ask yourself: What can a troll,
a flamer, or a spammer do to me anyway? Answer is: only
that which you allow them to do. Then ask yourself: What
could the gestapo[**] do to me?

 POWER CORRUPTS: ABSOLUTE POWER CORRUPTS ABSOLUTELY.

PS: Funny thing about threads requesting group
moderation... they have a tendency to digress into flame
wars -- ain't life a beach?

[*] That sanctimonious prick!
[**] Does gestapo qualify as evoking Godwins Law?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyMyth: Global variables are evil... WRONG!

2013-11-13 Thread Rick Johnson
On Wednesday, November 13, 2013 5:42:24 PM UTC-6, Rhodri James wrote:
 On Tue, 12 Nov 2013 02:06:09 -, Rick Johnson wrote:
  PyMyth: Global variables are evil... WRONG!
 That's not a PyMyth.  It's a CompSciMyth, or to be more
 accurate a good general Software Engineering guideline
 regardless of language.  Like all guidelines it can be
 broken, but people who break it should do so knowingly,
 aware that they have created potential problems for
 themselves.

You speak as if using globals are inhabited by gremlins
just wanting to get out and run a muck. There are no
inherent problems in the global interface design except
those that programmer inserts himself.

Real global variable interfacing is no different than
python object member interfacing, or module interfacing,
except that the latter two are encapsulated by inside a
namespace, and the former (historically) are unprotected and
available everywhere; hence the name global :-)

With Python, i can still reassign a value to class attribute
and break code that depends on that attribute, of course,
doing so is not a good idea; but it's allowed nonetheless!

The programmer can break ANY interface in Python, be it
accessing a module attribute he shouldn't touch or via a
real global variable (if Python had that functionality).

So that renders this whole argument of global gremlins as
FUD. The gremlins don't exist until the programmer creates
them. Just because one programmer is unable to create a
logical global implementation, does not mean another cannot.

All you need to do is adopt the principles of consistency.

But i'm not here to convince you that globals are correct
for you, nor do i want you to use them if you feel
uncomfortable (lord knows there's enough bad code
circulating already!) i just want people to stop propagating
this myth that globals are evil.

And i also want to point out the hypocrisy of Python's
design. Python DOES have globals


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


Re: PyMyth: Global variables are evil... WRONG!

2013-11-13 Thread Rick Johnson
On Wednesday, November 13, 2013 4:00:15 PM UTC-6, Andrew Cooper wrote:
 And what do you do when the wizards bend space-time to
 make PI exactly 3, for the ease of other calculations when
 building a sorting machine?

Are you telling me that these wizards can't be bothered to
write the integer 3? They have to reassign math.pi instead?

Look if you need some other granularity of PI besides
what's offered in math.PI, then do your own calculation.

The last thing you want to do is create a variable when a
constant is what you need.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyMyth: Global variables are evil... WRONG!

2013-11-13 Thread Rick Johnson
On Wednesday, November 13, 2013 6:17:22 PM UTC-6, Tim Daneliuk wrote:
  But python modules can't be interfaces because interfaces
  should protect internal data, prevent external forces from
  meddling with internal state (EXCEPT via the rules of a
  predefined contract), hide dirty details from the caller,
  and have clearly defined access points.
 BUT PYTHON MODULES DON'T FOLLOW THIS DESIGN PATTERN!
 I think this is an unfair criticism.   You can do this in
 ANY language if you know how.  For example, if I understand
 stack frames, I can write code that fiddles with local
 variables in compiled code.  For that matter, if I understand
 pointers at the assembler level, I can probably do the same
 with globals.

And if i understand file systems, and i have access to your
computer, i can delete the contents of your hard disc :-). We
can take this analogy all the way to it's absurd conclusions,
but we have not proven anything.

 Programming well has far less to do with the language and
 has far more to do with the designer and coder...

I very much agree. 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyMyth: Global variables are evil... WRONG!

2013-11-13 Thread Rick Johnson
On Wednesday, November 13, 2013 7:09:42 PM UTC-6, Steven D'Aprano wrote:
 On Wed, 13 Nov 2013 23:42:24 +, Rhodri James wrote:
  On Tue, 12 Nov 2013 02:06:09 -, Rick Johnson wrote:
  Python has globals, but we just can't admit it!
  A different subject entirely, but no more accurately stated.
 Completely inaccurately stated. It certainly isn't true
 that 99% of people  claim that Python has no globals.
 That would be a stupid thing to say for a language with a
 global keyword, 

Yeah, a global keyword that extends access ONLY as far as
module level scope -- hardly a *true* global.

 a globals function, 

Yeah, a globals function that returns the MODULE LEVEL
globals symbol table.

 and a built-in module that is shared across the entire
 process.

Now your thinking clearly. This is where Python's dirty
little secret globals live.

 Just because a module global alpha.spam is accessible to
 anything that imports the module doesn't make it a
 process-wide global. The ability to do this: import alpha
 alpha.spam = 23 does not make spam a process-wide
 global.

Oh lord, back to the fuzzy logic again :(
 
 It just means that attribute access on the module object
 is the supported interface for manipulating names in
 namespaces which are modules.

HUH? Was this last sentence an attempt to distract? We are
all quite aware that DOT access is the interface for
accessing module members, but what the hell does that have
to do with process wide globals?

No, your not going to so easily fool this audience with
slight of hand! In your generalized code example:

import alpha
alpha.spam = 23

Yes. spam is an attribute of module alpha, however, it is
also a global variable. Why?
 
  BECAUSE alpha.spam CAN BE MUTATED FROM ANYWHERE!

 There is very little practical difference apart from
 convenience between directly manipulating attributes as
 above, and using a setter function like setattr(alpha,
 'spam', 23). Python tries to avoid boilerplate.

Here you go again. Steven, we are ALL quite aware of these
facts, how is setattr germane to my complaints about globals?

 Since manipulating attributes is useful, a philosophy of
 consenting adults applies and we have direct access to
 those attributes, 

We don't have direct access, but access is an import away.

 with an understanding that we should use this power with
 care. With great power comes great responsibility -- if
 you're going to reach inside another module and manipulate
 things, you ought to know what you're doing.

Yes we must be careful, because these attributes are
ACTUALLY global. The fact that you have to use an import
statement to reach them does not alter the fact that they are
globally mutable.

 One of the
 numerous problems with process-wide globals is that
 there's no encapsulation and consequently one package's
 use of spam clobbers another package's use of spam for
 a different purpose. 

Exactly. That's why globals should be used intelligently.
There are many methods of creating an intelligent ordering
of global names so they don't clash. One of the most
simplistic is to tag all names with a prefix.

The best method is to have a namespace for globals that is
available everywhere WITHOUT import and accessed via a
single letter (you could emulate this now in Python by
injecting a namespace into sys.modules). In this manner,
globals will be both easily accessible, qualified (no need
for prefixes), and available WITHOUT messy imports

 But that's not the case here: alpha's spam is separate
 from module omega's spam variable. To give an analogy:
 [snip analogy]

Steven you're going off into la-la land man. Are you
suggesting that because two modules can contain the same
name that module attributes are not global?

I love how you support the duck typing paradigm UNTIL it
interferes with your argument. Sure, under Python's current
implementation of globally mutable module attributes you
can have the same name stored in different modules all with
different values, but they're still GLOBALS!

Because I can reach in and access them OR mutate them from
ANYWHERE! That's the very definition of a globally
accessible variable (aka: global variable)

AND THIS IS WERE THE HYPOCRISY COMES IN. 

Since python modules have no set/get interface restrictions,
ALL attributes are globals!


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


Re: PyMyth: Global variables are evil... WRONG!

2013-11-13 Thread Rick Johnson
On Wednesday, November 13, 2013 8:45:16 PM UTC-6, Steven D'Aprano wrote:
  A fully-auto machine gun with a hair-trigger and no
 safety is no  different from a single-barrel shotgun with
 a safety and a trigger lock!  You can blow your foot off
 with both!  

Yes. But in the case of the shotgun you'd have to find the
key, unlock the trigger, unset the safety, and aim REALLY
well... because your only getting off one shot, and if you
miss or only wound me, i've got that full auto machine gun
with hair trigger and no safety -- i won't need to live very
long to return the favor. :)

 Yes, but in the first case you can do it by
 accident, while with the  second you have to work hard to
 blow your foot off.

Uh huh. 

And why do i have the sneaking suspicion that the BIG SCARY
ASSAULT WEAPON is referring to my argument and the old
shot-gun that Grandpa has in the closet under lock and key
is your argument.

But more importantly, why is all this straw scattered across
the floor? 

Very strange.

Very strange indeed.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyMyth: Global variables are evil... WRONG!

2013-11-13 Thread Rick Johnson
And what's this?

*picks up hat*

Where did this hat come from???

Spectator interrupts: Maybe Steven threw his hat in?

No, no. 

Can't be. 

Steven would not wear something this old. 

I mean, it looks like something a farmer would put on a
scarecrow or something???

*scratched head*

OH MY GAWD!

*throws hat on floor*

That hat has crow poop on it!

Could someone PLEASE get a janitor in here to clean this
mess up! 

For Christs sakes we're trying to have a technical
discussion here and some prankster goes and tosses a
straw grenade right in the middle of it!

How rude!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Automation

2013-11-13 Thread Rick Johnson
On Sunday, November 3, 2013 5:32:46 PM UTC-6, Denis McMahon wrote:
 Seems to me like you're using a sledgehammer to shell a peanut.

And hopefully he knows whether or not he has a peanut allergy 
before he commits to enjoying the fruits of his labor.


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


Re: Automation

2013-11-13 Thread Rick Johnson
bob gailer wrote:
 Does this have anything to do with statistics? Quantum
 theory? Telephony?
 
 P = Pluto, V = Venus, S = Saturn?

 Help us understand - then we *might* be able to help you. 

bob later gailer wrote:
 Oh ... will you please explain in good English and a lot
 more detail. I can only begin to guess from that what you
 want. Guessing wastes all our time.

bob even later gailer wrote:
 Let's remember that it is the job of the OP to explain his
 problem so we can offer solutions.

bob gailer always writes:
 Bob Gailer
 XXX-XXX-
 XX  XX

Urm Bob, i'm see you're getting off to a wonderful start
here, but it might behoove you to know that including any
personal contact information in your emails in not a good
idea. In fact it's quite dangerous.

This is a PUBLIC group after all, and not only is that
information available to ALL group members (for better or
worse) but it's available to everyone on the internet.

Just uh, FYI there fella.

Cheers.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyMyth: Global variables are evil... WRONG!

2013-11-13 Thread Rick Johnson
On Wednesday, November 13, 2013 10:33:22 PM UTC-6, Roy Smith wrote:
 Wait, aren't you the guy who's into MUDs?

Yes he is. 

But that's his second favorite hobby. 

His first is filling the Devils Advocate slot when 
Steven is too busy -- doing WHATEVER Steven does when 
he's not here. God only knows.

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


Re: PyMyth: Global variables are evil... WRONG!

2013-11-14 Thread Rick Johnson
On Wednesday, November 13, 2013 11:50:40 PM UTC-6, Steven D'Aprano wrote:
 On Wed, 13 Nov 2013 19:45:42 -0800, Rick Johnson wrote:
  On Wednesday, November 13, 2013 8:45:16 PM UTC-6, Steven D'Aprano wrote:
   A fully-auto machine gun with a hair-trigger and no
  safety is no  different from a single-barrel shotgun with a safety and
  a trigger lock!  You can blow your foot off with both!
  Yes. But in the case of the shotgun you'd have to find the key, unlock
  the trigger, unset the safety, and aim REALLY well... because your only
  getting off one shot, and if you miss or only wound me, i've got that
  full auto machine gun with hair trigger and no safety -- i won't need to
  live very long to return the favor. :)
 I think you're missing the point that we're talking about the coder 
 shooting themselves in the foot, not Gunfight At The OK Corral. There's 
 no favour to return. 

And you missed the point that i took your straw-man and
converted him into satire. You owe me gratitude for
*politely* ignoring your repeated logical fallacies.

 Yes, the point is that process-wide global variables are
 demonstrated by 50+ years of programming experience to be
 best avoided (in general -- there are caveats and
 exceptions of course). We're talking about probably
 millions of person-hours of experience leading to the
 conclusion that globals are harmful.

But yet Python has globals, you just have to *import* them.
But that design is flawed

 It isn't that global variables will leap out of the
 computer and attack you while you sleep,

Funny, that sounds like my argument from earlier. Something
about gremlins.

 of course, but that in general *its too damn hard* for
 human programmers to write good, reliable, maintainable,
 correct (i.e. bug-free) code using process-wide global
 variables.

Complete FUD. Maybe for you. Not for me.
 
 Global variables are the spaghetti code of namespacing --
 everything is mixed up together in one big tangled mess.

It's a tangled mess if you design it to be a tangled mess. 

 The more global variables you have, the worse the tangle. 

Complete illogic. 

What if all the globals are only accessed
and never mutated? You could have a million globals that never
change (of course they'd technically be constants) and never
suffer a single error from globals EVEN IF your an incompetent
software designer.

 One or two is not too bad. With good conventions for
 encapsulation to limit the amount of tangled, coupled code
 (e.g. naming conventions, or limiting globals to a single
 module at a time by default) the amount of harm can be
 reduced to manageable levels.

 SO now your agreeing that globals are not evil again. I
 positied an anaology in a passed thred that went something
 like this:

ManufacurerA claims his car is the safest on the road.

ManfacturerB drives ManfacturerA's car into a ditch and then
claims ManfacturerA is a liar.

Result: Who is wrong?

 Global variables increases coupling between distant parts
 of the code. I remember a nasty little bug in Windows
 where removing IE stopped copy-and- paste from working
 everywhere. That's a sign of excess coupling between code
 -- there's no logical reason why removing a web browser
 should cause copying text in Notepad to fail.

Do you have link describing this bug? I am not aware of such
bug ,but uh, i would not at all be surprised that windows
could break from removing that gawd awful IE.

Come to think of it, i'll bet it's not even a bug at all,
but a feature to prevent wise users from removing IE,
thereby maintaining IE's footprint in the wild. 

Steven, this sounds more like Fascism than clumsy use of
globals to me.

But even IF globals are to blame, by removing IE, you have
removed a large chunk of code from a code base that was not
designed for modularity. (We could argue whether or not
windows should allow removal of IE, but ultimately that is
M$ decision)

No developer could possibly forecast every possible bad
thing a user might decide to do. Especially when we're
talking about ripping components of the software out
completely.

Do i think IE should be a removal component? HECK YEAH, and
i would have designed it that way. But IS is not my baby, it
belongs to Mr. Gates, and he designs his software any way he
damn well pleases, and you and i can choose not to use it.

Image if someone downloaded Python and just started ripping
out source files willy-nilly because they did not like them
for whatever reason. Then, they came to this list and start
bitching because Python was blowing chunks. And don't give
examples of things that can be ripped out without breaking
Python, because that is germane either.

How would you respond to such complaints? 

Hmm...never thought you'd be agree with Mr. Gates did ya?

 We want to avoid unnecessary coupling: opening your fridge
 door shouldn't flush the toilet.

*KAH-BOOM* (Straw-bomb expodes)(AGAIN!)

 Since global variables increase coupling, and coupling is
 often harmful, one way

Re: PyMyth: Global variables are evil... WRONG!

2013-11-15 Thread Rick Johnson
On Friday, November 15, 2013 2:19:01 AM UTC-6, Steven D'Aprano wrote:

 But with software, coupling is *easy*. By default, code in
 a single process is completely coupled. Think of a chunk
 of machine code running in a single piece of memory. We
 have to build in our own conventions for decoupling code:
 subroutines, local variables, objects, modular code, and
 so forth. Physical objects are inherently decoupled. Code
 is inherently coupled, and we need conventions to decouple
 it. One of those conventions is to prefer local variables
 to global variables, and another is to limit the scope of
 global variables to per module rather than process-wide.

You're thoughts on coupling and decoupling
of design architecture is correct, but you only argue for
your side :-). Allow me to now argue for my side now.

And i want to leave the safe world of general analogies
and enter the dark esoteric word of flawed software design.

And since people only want to give me credit when i talk
about Tkinter, well then, what better example of bad design
is there than Tkinter? Hmm, well there's IDLE but that will
have to wait for another thread.

Let's see... Tkinter's design today is a single module
containing a staggering:

155,626 chars

3,733 lines

30 classes 

16 functions

4 puesdo-constants (Python does not support true
constants!)

10 module level variables (3 of which are mutated from
nested scopes within the module itself)

Unwise use of a global import for the types module, even
though only a few names are used -- AND there are
better ways to test type nowadays!

Unwisely auto-imports 82 Tkinter constants.

Only OpenGL is more promiscuous than Tkinter!  

But let's stay on subject shall we!


  The Road To Recovery:


The very first thing a wise programmer would do is create a
package called tkinter. Then, he would export all class
source code to individual sub-modules -- each module being
the class name in lowercase.

AND VOILA! 

Even after only a simple half hour of restructuring, the
code is starting to become maintainable -- IMAGINE THAT!


BUT DON'T GET YOUR ASTROGLIDE OUT YET FELLA! 

WE'VE GOT MORE WORK TO DO!

Just as the programmer thought all was well in toon
town, he quickly realizes that since Python has no
intelligent global variable access, and his sub-modules need
to share data with the main tkinter module (and vise versa),
he will be forced to write:

from tkinter import var1, var2, ..., varN

IN EVERY DAMN SUBMODULE that needs to access or
mutate one of the shared variables or shared
functions.

Can anyone tell me why sharing globals between sub-packages
is really so bad that we have to import things over and
over?

And if so, would you like to offer a cleaner solution for
the problem? 

And don't give me the messy import thing, because that's 
not elegant!

WHY IS IT NOT ELEGANT RICK?

Because when i see code that accesses a variable like this:

var = value

I have no way of knowing whether the mutation is happening
to a local variable, a module level variable, or even a true
global level variable (one which extends beyond the
containing module).

Sure, i could search the file looking for imports or
global declarations, but why not use self documenting
paths to global variables?

The best solution is to create a global namespace. You could
name it G. So when i see a mutation like this:

G.var = value:

I will know that the mutation is happening to a REAL global
variable. But, even that information is lacking. I need
more... What i really want to see is this:

G.tkinter.var = value
  
Boom baby! Every thing i need to know is contained within
that single line without import everywhere.

   I am accessing a global variable
   I am accessing a global variable for the tkinter package
   The variable's name is var
  
It's explicit, but it's not SO explicit that it becomes
excessive, no. I would much rather type just a FEW more
characters than scour source code looking for obscure clues
like global declarations, imports, or whatever foolish
design you can pull out of your arse!

And what about the mysterious run-time injected
global, how the heck are you planning to handle
that one with imports?

I just want to access globals in an logical and consistent
manner via a clean interface which will alleviate all the
backtracking and detective work that causes us to lose focus
on the main architecture of our software.

Because,

EXPLICIT IS BETTER THAN IMPLICIT.
 
And, 

FOCUS IS BETTER THAN FRUSTRATION!

Is that really too much to ask? 

Must i create a hack (C.py and G.py) for every missing or
broken feature in this damn language?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Fire Method by predefined string!

2013-11-17 Thread Rick Johnson
On Sunday, November 17, 2013 3:46:16 PM UTC-6, Tamer Higazi wrote:

 class(object):
 def Fire(self,param)
 #possible ?!
 self.__param():
 def _DoSomething(self):
 print 'I did it!'

1. First off your class declaration is not valid -- it needs
an identifier!

2. Never start a function or method with a lowercase letter.
Please read PEP8

3. I would advise using self documenting names.

class Foo(object):
def envokeMethodByName(self, name):
...

But what if the method takes arguments? :)

class Foo(object):
def envokeMethodByName(self, name, *args, **kw):
getattr(self, name)(*args, **kw)

But what if want to restrict the methods?

class Foo(object):
def __init__(self):
self.allowedNames = [
play,
pause,
eject,
]
def envokeMethodByName(self, name, *args, **kw):
if name not in self.allowedNames:
raise DontAbuseMyInterfaceMan(!)
getattr(self, name)(*args, **kw)

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


Re: Fire Method by predefined string!

2013-11-17 Thread Rick Johnson
On Sunday, November 17, 2013 4:23:11 PM UTC-6, Rick Johnson wrote:

 2. Never start a function or method with a lowercase letter.
 Please read PEP8

Urm... let me correct that:

2. Never start a function or method with a UPPERCASE letter.
Initial uppercase should be reserved for class names only --
and any number of leading underscores does not affect that
rule because underscores are not in the set [A-Za-z]!

You don't want these:

  def __IllegalName
  def _IllegalName
  def IllegalName

But these are okay:

  def __legalName
  def _legalName
  def legalName

These are preferred, however, i detest superfluous underscores!

  def __legal_name
  def _legal_name
  def legal_name
 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Oh look, another language (ceylon)

2013-11-17 Thread Rick Johnson
On Saturday, November 16, 2013 9:41:07 PM UTC-6, Gregory Ewing wrote:
 The type system looks very interesting!

Indeed.

I went to the site assuming this would be another language
that i would never like, however, after a few minutes
reading the tour, i could not stop!

I read through the entire tour with excitement, all the while
actually yelling; yes and sometimes even yes, yes, YES

But not only is the language interesting, the web site
itself is phenomenal! This is a fine example of twenty first
century design at work.

I've always found the Python web site to be a cluttered
mess, but ceylon-lang.org is just the opposite! A clean and
simplistic web site with integrated console fiddling --
heck, they even took the time to place a button near every
example!

Some of the aspects of ceylons syntax i find interesting are:

Instead of using single, double, and triple quotes to
basically represent the same literals ceylon decided to
implement each uniquely. Also, back-tick interpolation
and Unicode embedding is much more elegant!

The use of a post-fix question mark to denote a
declared Type that can optionally be null.

The ceylon designers ACTUALLY understand what the
word variable means!

Immutable attributes, yes, yes, YES!

The multiplication operator can ONLY be used on
numerics. Goodbye subtle bug!

Explicit return required in methods/functions!

No default initialization to null

No omitting braces in control structures
(Consistency is the key!!!)

The assert statement is much more useful than
Python's

The tagging of iterable types using regexp
inspired syntax * and + is and interesting idea

Conditional logic is both concise and explicit using
exists and nonempty over the implicit if value:

Range objects are vastly superior to Python's lowly
range() func.

Comprehensions are ordered more logically than
Python IMO, since i want to know where i'm looking
BEFORE i find out what will be the return value


Ceylon: [for (p in people) p.name]
Python:[p.name for p in people]
Ruby: people.collect{|p| p.name}

Ceylon: for (i in 0..100) if (i%3==0) i
Python: [i for i in range(100) if i%3==0]
Ruby: (1..10).select{|x| x%3==0}

Funny thing is, out of all three languages,
Ruby's syntax is linear and therefor
easiest to read. Ruby is the language i
WANT to love but i can't :( due to too many
inconsistencies. But this example shines!

 It's just a pity they based the syntax on C rather
 than something more enlightened. (Why do people
 keep doing that when they design languages?)

What do you have in mind?

Please elaborate because we could use a good intelligent
conversation, instead of rampant troll posts.

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


Re: Oh look, another language (ceylon)

2013-11-18 Thread Rick Johnson
I've never *really* been crazy about the plus operator
concatenating strings anyhow, however, the semantics of +
seem to navigate the perilous waters of intuition far
better than *.

Addition of numeric types is well defined in maths:
Take N inputs values and *reduce* them into a single
value that represents the mathematical summation of
all inputs.

HOWEVER, 

Addition of strings (concatenation) requires
interpreting the statement as a more simplistic
joining process of : take N inputs and join them
together in a *linear fashion* until they become a
single value.

As you might already know the latter is a far less elegant
process, although the transformation remains sane. Even
though in the first case: with numeric addition, the
individual inputs are *sacrificed* to the god of maths; and
in the second case: for string addition, the individual
inputs are *retained*; BOTH implementations of the plus
operator expose a CONSISTENT interface -- and like any good
interface the dirty details are hidden from the caller!

INTERFACES ARE THE KEY TO CODE INTEGRITY and LONGEVITY!

HOWEVER, HOWEVER. O:-)

There is an inconsistency when applying the * operator
between numerics and strings. In the case of numerics the
rules are widely understood and quite logical, HOWEVER, in
the case of string products, not only are rules missing,
any attempt to create a rule is illogical, AND, we've broken
the consistency of the * interface!

py a * 4
''

Okay, that makes sense, but what about:

py a * 

That will haunt your nightmares!

But even the previous example, whilst quite logical, is
violating the contract of transformations and can ONLY
result in subtle bugs, language designer woes, and endless
threads on Pyhon-ideas that result in no elegant solution.

THERE EXISTS NO PATH TO ELEGANCE VIA GLUTTONY

Operator overloading must be restricted. Same goes for
syntactic sugars. You can only do SO much with a sugar
before it mutates into a salt.

TOO MUCH OF A GOOD THING... well, ya know!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Got a Doubt ! Wanting for your Help ! Plz make it ASAP !

2013-11-23 Thread Rick Johnson
On Friday, November 22, 2013 8:18:03 PM UTC-6, Steven D'Aprano wrote:
 [snip] I look forward to the day that rice is the plural of ri 

Yes and i look forward to the day when thread hijacking perpetrated under the 
guise of exploring linguistic minutia perpetrated under the guise of vanity 
is frowned upon. 

PS: The only method chaining going on here is via the .brown_nosing() method.

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


Re: Got a Doubt ! Wanting for your Help ! Plz make it ASAP !

2013-11-23 Thread Rick Johnson
On Friday, November 22, 2013 8:18:03 PM UTC-6, Steven D'Aprano wrote:
 As this is an international forum, it behoves us all to make allowances 
 for slight difference in dialect.

I don't thank so. What purpose does that serve?

If we allow people to speak INCORRECT English under the
guise of political correctness then no one will benefit.
The speaker will continue using the language improperly and
his audience will continue to be confused.

 But Rick, we don't want to offend people!

Piss off you spineless invertebrate!I would be more offended
if people did NOT correct me. People correct you when they
WANT you to learn, likewise, people tolerate you when they
want you to remain inferior.

 Tolerance and apathy are the last virtues of a dying society

Only those societies with a vision for the future will
survive, that is, until they inevitably grow tired from the
intense competition and lose their vision THEN apathy sets
in and a NEW society steps in to fill the vacuum.

 Competition is the engine that drives the cogs of evolution

You are all but pawns in a greater game. It is better to die
fighting for SOMETHING, then to wither away intolerant of
NOTHING. There exists no utopia. And any pursuit of such
ends is foolish.

Have you ever even considered what sort of disgusting filth
humans would degenerate into if we achieved a utopia free
from competition? What would we do all day? What purpose
would our lives fulfill?

 Would you eat if you were never hungry?

Evolution will NEVER allow such a dismal state to prosper,
no, it will stamp out every attempt by convincing the strong
to conquer the weak -- and to do so with extreme prejudice!

The system abhors the weak; the system ridicules the weak;
because the weak serve no end but their own selfish and feeble
attempts to convince themselves they are not but lowly pawns.

 Time to pull your head out of the sand!

People like you don't want to accept the truth, you want to
believe that living in harmony is the answer. No, harmony
is a death wish. If you wish to reach a state of harmony,
then not only are you suicidal but you're homicidal also
because you obviously don't care about your fellow human
beings future progression.

If however, you cared about what really matters, you would
advise our Indian friend to speak better English. By
learning proper English he can become a productive member of
this society -- maybe one day even contributing something
remarkable.

But until his communication can rise above the level of a
3rd grade public school student in rural Kentucky, he is
draining resources instead of creating them!I WANT our Indian
friend to become proficient so that he *might* one day be a
*worthy* advisory for me to challenge.

Anyone can defeat the weak, only the strong have a snowballs
chance in hell to defeat the strong.

 Who said chivalry was dead?

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


Re: Got a Doubt ! Wanting for your Help ! Plz make it ASAP !

2013-11-25 Thread Rick Johnson
On Saturday, November 23, 2013 7:38:47 PM UTC-6, Steven D'Aprano wrote:
 Where do you, an American,

What the hell makes you believe I'm an American? Because i
speak fluent English? Because i embrace capitalism? Because
i wish to be free of tyranny? Well, if that's all it takes
to be an American, then count me in!

America.append(RickJohnson)

 get off telling others that their regional variety of
 English is incorrect?

Because with the ALREADY excessive polysemous nature of the
English language, why would we want to PURPOSELY inject more
inconsistency?.. especially when the sole purpose of the
change is driven by selfishness?

Do you remember your thread titled: The narcissism of small
code differences? Do you remember how the author warned
against the dangers of re-writing old code for fear of
enduring lengthy de-bugging trials?

Okay, with that synopsis in mind, now you want us to believe
that injecting polysemy into the English language JUST for
the mere PRIDE of regional groups is not:

  destructive?
  or at least harmful?
  or at minimum, non-productive?

 Sod off and take your despicable little Randian pseudo-
 philosophy with you.

Yes because women couldn't *possibly* be legitimate
philosophers -- is that correct? Or is your chauvinist anger
towards Ayn merely a mask to disguise the *real* source of
hatred: the defection of a fellow comrade to the
capitalist system?

How dare people allow themselves to be free! 

HOW DARE THEY!

...who's the fascist now?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Excute script only from another file

2013-11-25 Thread Rick Johnson
On Monday, November 25, 2013 4:52:46 AM UTC-6, Himanshu Garg wrote:

 My motive is I will give scripts to somebody else and he
 should not run the script directly without running the 
 parent script.

The only sure fire method to prevent a file containing
Python code from executing on a machine with Python
installed is to use an extension that the system will not
associate with Python.

 ScriptFolder/
   script.py
   mod_1.ignore
   mod_2.ignore
   ...

Of course, any other Python module that needs to leverage
the API contained within the aliased mod files will need
to do so *manually*:

 1. Read the file from disc
 2. Evaluate the file contents and make callable
 3. Close the file

Sounds like your distributing a Python application and need
a simplistic method by which non-techies can run the code,
but as we all know:

 fools are too cleaver!

Of course a smarty pants could could change the extension to 
py[w], but that would be violating your interface. :) 

Another choice would be to use a package.

 ScriptPackageFolder/
   __init__.py
   __script.py
   mod_1.py
   mod_2.py
   ...

But nothing could stop them from accessing the contents of
the package directory. 

A third alternative would be to install the support modules
in a place that the user would be unlikely to look and then
place a mainscript somewhere that is easily accessible. But
even this method will not prevent the running of py scripts.

Sounds like my first offering is the best. At least with 
that method they would be forced into an explicit act of 
renaming the file before they violate your interface.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Got a Doubt ! Wanting for your Help ! Plz make it ASAP !

2013-11-25 Thread Rick Johnson
On Monday, November 25, 2013 2:10:04 PM UTC-6, Ned Batchelder wrote:
 Let's please avoid veering off into rants about language
 and philosophy now.

Hello Ned. I respect the fact that you want to keep threads
on-topic, and i greatly appreciate the humbleness of your
request.

However, i feel as though i am being unfairly treated when
other people (who shall remain unnamed) started the
discussion in an off-topic direction long before i chimed
in.

And to be fair, i was merely retorting a hasty assertion by
our friend Steven. Yes, i might have gotten a bit
philosophical in the process, but the reply itself was
germane to the sub-topic that Steven propagated up.

Furthermore, I don't believe that applying ridged rules of
topicality are to the benefit of anyone. Conversations of
any topic are destined to spin-off in many seemingly 
unrelated directions -- and this is healthy!

As a spectator (or a participant) you can choose to stop
listening (or participating) at anytime the conversation
becomes uninteresting to you.

Some of the greatest debates that i have participated
in (those that result in epiphany or even catharsis) had
initially sprung out of seemingly unrelated subject matters
which slowly built to a crescendo of maximum intensity.

I don't think we should attempt to restrict debate since it 
is this very debate that results in evolution of not only
the participants, but also the spectators.

Man's mind is his basic tool of survival. Life is
given to him, survival is not. His body is given to
him, its sustenance is not. His mind is given to
him, its content is not

[...]

Reason does not work automatically; thinking is not
a mechanical process; the connections of logic are
not made by instinct. The function of your stomach,
lungs or heart is automatic; the function of your
mind is not.

In any hour and issue of your life, you are free to
think or to evade that effort. But you are not free
to escape from your nature, from the fact that
reason is your means of survival -- so that for you,
who are a human being, the question to be or not to
be is the question to think or not to think.

-- Ayn Rand

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


Re: Excute script only from another file

2013-11-25 Thread Rick Johnson
On Monday, November 25, 2013 8:41:07 PM UTC-6, Chris Angelico wrote:

 Totally sure-fire. Absolutely prevents any execution until it's
 renamed. 

Doh! It seems Python's quite the sneaky little snake!

 By the way, what does associate mean, and what does it have
 to do with file names?

Hmm, I did not see his command line snip-it and assumed his users where not 
command line savvy, therefor they would be running the script via a mouse 
click -- still probably not sure fire advice either. 

Okay, Rick was wrong once. get over it! :-P
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Got a Doubt ! Wanting for your Help ! Plz make it ASAP !

2013-11-26 Thread Rick Johnson
On Tuesday, November 26, 2013 8:52:11 AM UTC-6, Chris Angelico wrote:
 On Wed, Nov 27, 2013 at 1:37 AM, Roy Smith [...] wrote:
  We live in an international world (otherwise we wouldn't
  need that annoying unicode stuff).  When you say,
  effort to be understandable, what you're really saying
  is, everybody should be just like me. Unfortunately,
  that's not going to happen.  Or maybe fortunately, since
  variety and exploring different cultures is part of what
  makes life interesting.

Agreed. Exposing oneself to new experiences is greatly
beneficial to ones understanding of the world.

However, you (and Chris, and Tim) seem to be ignoring the
500lb gorilla in the room, and are only concerned with
chastising the people who are complaining about the
offensive odors the animal's feces is emanating.

Even if you are correct that the OP is using a regional
variation of English, you fail to realize that this
regional redefinition of the English word: doubts to
mean what the *majority* of  English speaking world
understands as questions, cannot be justified OUTSIDE of
his region.

It's not like he's using a NEW word; a word that has never
been defined, NO, his region has redefined a widely
understood word. Imagine if he used a NEW word:

My curflabals are:
  1. blah
  2. blah
  ...

My boygenjoygens are:
  1. blah
  2. blah
  ...

In the previous examples we show that introducing a NEW word
is fine, because, at least when we encounter a NEW word we
will *instantly* know that we need to find a definition for
the NEW word BEFORE we can *fully* comprehend what the
author is trying to tell us.

So when we see the word questions followed by an
enumerated listing, we know that that the author seeks
*specific* answers to *specific* questions and is requesting
those answers from a mostly unemotional point of view
(inquisitiveness).

HOWEVER,

When we see the word doubts, followed by an enumerated
listing, we falsely believe the lad is confused or has some
level of concern. In other words, he is asking for answers
but his request is the result of an internal emotional
distress, therefor, not only will he need his questions
answered directly, he also requires a deeper understanding
of the problem (and maybe even coddling) BEFORE he can
equalize his emotional state to acceptable levels.

HELPING SOMEONE EXCOMMUNICATE THEMSELVES OF DEMONIC
EMOTIONAL DISTRESS IS A NOBLE PURSUIT, HOWEVER,
SANCTIONING THE ILLOGICAL DISCOMBOBULATION OF
DEFINED WORDS FROM THEIR UBIQUITOUS DEFINITIONS CAN
BE NOTHING LESS THAN ILLOGICAL SUICIDE BY EMOTION.

Now... *hopefully* we can understand why the words question
and doubt should NEVER be used interchangeably.

But for those of you who still seek coddling, read on...


  When you say, effort to be understandable, what you're
  really saying is, everybody should be just like me.


That sword can cut both ways friend.

But let's take a step back, drop the knee jerk politically
correct emotional responses, and look at this issue from a
objective point of view.

Most arguments supporting the OP's incorrect use of doubt
are suggesting that we must be open to regional uses of
English, even if those uses are illogical? They chastise us
for even thinking that WE are the final judges of what
doubt should mean.

Okay, that's fair. To be impartial we must provide evidence
to back up our logical claims. But who could possibly be
impartial?

 We shall consult the oracle!

In every country in the world there exist a Guru, a virtual
Guru who can answer almost any question; define almost any
word; and find almost anything your filthy little fingers can
peck into a keyboard.

  Surprise! i'm talking about GOOGLE.

Since the ENTIRE world knowledge is available online, let's
allow the Google mind hive to decide our petty little
problem for us, eh?


 Your challenge, if you choose to accept it:

Can someone, ANYONE, show me a *respectable* dictionary or
online definition database that defines the word doubt as
the OP intended? Remember, it must be in English!


 The reality, if you choose to believe it:

But even IF you *can* show me one, or even a couple of measly
examples, do you *REALLY* expect that your hand-full of
examples can tilt the balances of reason and logic in your
favor AGAINST the mountains of evidence that clearly judges
the OP's use of doubt to be wrong?


 The result, if you choose to fight it.

 Going... Goooing. GONE!
 Rick has done it again!
 A new home-run 

Re: Excute script only from another file

2013-11-26 Thread Rick Johnson
On Tuesday, November 26, 2013 5:09:13 PM UTC-6, Chris Angelico wrote:
 My point was that Rick had made the assumption that the GUI was
 *everything* and that users were able to do nothing beyond
 double-clicking on icons

For some people the GUI *is* everything. 

Most people are unaware that life *even* exists beyond the
point and click. Heck, If you opened a command prompt in
front of them, they'd run and hide in a closet for the next
three hours consumed with fear. They'd probably convince
themselves that cryptic commands in a black window could
be nothing less than sorcery -- and that's usually when the
pitchforks come out.

Chris, it's obvious you need to climb down from the tower
and mingle with the peasants a bit -- don't worry, we'll
delouse you when you get back ;-)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Experiences/guidance on teaching Python as a first programming language

2013-12-16 Thread Rick Johnson
On Tuesday, December 10, 2013 7:35:47 PM UTC-6, Dennis Lee Bieber wrote:

 NAILS Nails were verboten in my high school wood
 working class... We used dowels and glue; chisels to carve
 dove-tails; etc.

That could be a result of two possibilities:

1. Your high school years were before the great war, or:
2. Your wood shop teacher was a Luddite, a sadist, or both!

FYI: Fastener technology has come a long way since the fall
of the of the Amish empire. All that laborious joinery has
been surpassed by mass production of helical threads and
pneumatic drivers. What once took a master craftsman an
entire day to build could now be built by a novice in mere
minutes.

  Dovetails are nothing more than sadistic nostalgia --
  they give old men a chubby and young men a nightmare.
  
When are we going to realize that the goal, *ahem*, OUR
GOAL, is to delegate minutiae DOWNWARDS, building the
collective knowledge base layer by layer...

ABSTRACTIONS people, ABSTRACTIONS!!!

Because, when you've got all your mental focus attuned to
carving intricate inter-meshing teeth into dense hardwoods
using razor sharp hand tools, you will be unable to see the
big picture, and furthermore, you might slip and cut your
finger off!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Experiences/guidance on teaching Python as a first programming language

2013-12-16 Thread Rick Johnson
On Monday, December 9, 2013 2:53:30 PM UTC-6, bob gailer wrote:
 Taking the opposite perspective from Gene: I think Python
 is great as an intro to computing and programming. Give a
 student a tool with which he can be productive quickly.
 and with minimal effort. Understanding the real machine
 may be of interest to some but is not essential .I'd make
 that later and optional. Do you teach potential drivers
 how the engine works before letting them drive?

No, not a scientific understanding of the process by which
chemical energy is converted to mechanical energy, or even the
demanding study of fuel efficiency, or much less the historical
evolution of engines from the time of the Aeolipile

But, as with any mental evolution, many tangential areas
of study need to be considered for both the wholistic and
practical application of said knowledge.

The first course of study for any would be motor vehicle
operator is the fundamental forces of classical physics that
effect ALL bodies in motion -- acceleration, velocity,
inertia, blah-blah-blah, but, more importantly, how these
forces are amplified to extreme danger during the operation
of a motor vehicle.

Secondly even though a student of motorized locomotion
need not understand the inner workings of an internal
combustion engine, he would behoove himself to study some
basic and practical knowledge of the generalized system.

  1. A modern motor vehicle converts chemical energy
  stored in fuel into mechanical energy via and internal
  explosion. The major components of a modern motor
  vehicle include: Engine, Transmission and Drive-train
  -- Nuff said.

  2. Mechanical components require fluids to reduce
  friction and remove heat from the system, therefore, a
  working knowledge of fluid levels and locations is
  vital.

Furthermore, fluids are color coded. Oil is black; most
transmission fluids are red; coolant is colored yellow
(or green) and mixed with water.

**As a side note, you might want to be aware that
ethylene glycol, whilst quite poisonous, tastes
sweet. That fact may seem inconsequential until your
beloved pet drinks leaking coolant water, quickly
goes blind, and dies a slow horrible death.

  3. Vehicles require lights and signals for safety and
  useability. An understanding of the proper locations
  and procedures for periodic testing is vital to safe
  operation. Same for other safety devises and interfaces.

  4. Obviously some rules of the road are applicable.
  Your car will not be the ONLY vehicle on the road,
  therefor your must understand how to interface with
  other drivers, navigate adverse road conditions, and
  react to unexpected situations that can arise at any
  time.


 Conclusion:

The main points i outlined are merely a blip on the radar of
the many tangential points of study, however, they are quite
relevant to proper operation of a motor vehicle. Most of you
can probably draw the parallels to programming from these
examples.

My opinion is that problem solving should be covered before
any language is even discussed or any code is written. Too
many people lack basic problem solving skills. Look, if you
can't write up (or imagine) the general steps that are
required to solve your problem, then how the heck do you
expect to write code to solve the problem?

And let's just get one thing strait from day uno for all you
perspective programmers out there:

  If the idea of banging your head on a desk for days
  only to find out that some stupid API does not work as
  expected, or was poorly designed, or that, GOD
  FORBID... you made the dumbest mistake ever!

  Ha Ha Ha!

  If the idea of that kind of mind numbing detective
  work is not fun for you, well, you're in good company
  because i don't always enjoy it either...

  HOWEVER!

  if you're not driven by the satisfaction of finding
  the answer; by a burning desire to solve the problem;
  by an unflinching will not to be defeated by any bug
  -- because the answer is always out there, you just
  have to find it -- well then, programming might not be
  for you.

But i'm just wasting my time because soon you'll discover
Python list and Stack overflow and from these sources flows
an endless supply of free labor.

  Teach a man to Google and others program for a day.
  Teach him to problem solve, and he programs for life.

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


Re: Experiences/guidance on teaching Python as a first programming language

2013-12-16 Thread Rick Johnson
On Monday, December 16, 2013 8:33:11 PM UTC-6, Steven D'Aprano wrote:

 Of course, this is very hard to measure: different languages require
 different amounts of code to get something useful done. Different
 languages get used for different things -- there are no operating system
 kernels written in COBOL, although there are plenty of business apps
 written in C. There are vast differences in software methodologies. But I
 think that people intuitively grasp that if something is hard to learn,
 as C is, chances are very good that it is equally hard to use even for
 experts. Why do you think that C programs often have so many bugs and
 vulnerabilities, such as buffer overflows and the like? It's not just
 down to lousy coders.

I have a real life example of such horrendous design flaws
involving a highway intersection. A while back, can't
remember when, a friend of mine was involved in an accident
that was his fault. This surprised me because i consider
this person to be a very cautious driver.

After checking records, i was amazed to find a high
occurrence of traffic incidents that mirror the exact
conditions of my friends accident, and in almost every
incident, the person at fault runs the thru the red light.

This seemed odd because how could so many people be making
the same mistake? The sheer number of signal violations
would exclude malevolent intentions.

So being the curious chap i am, i investigated further. I
myself traveled the course my friend took the day of the
fateful accident.

The course involves starting from a traffic signal on one
side of the freeway, following a long left turn lane under
the freeway, and then emerging on the other side to cross the
opposing feeder road -- it is a this point that the
accidents happen with great frequency!

There are two distinct design flaws contributing:

  1. The bridge itself is obscuring the view of the
  second signal. The second signal is not visible until
  the motorist are very close -- much too close in my
  opinion!

But i feel #2 is the *real* contributing factor!

  2. The second signal and the first signal are not
  synchronized, creating an inconsistency between both
  signals. For example, sometimes you can catch both
  lights green, but sometimes, the second light will
  change unexpectedly whilst you're navigating the long
  left turn, THUS requiring all traffic to stop under the
  freeway before crossing the opposing feeder road.

  ...and the results of this poor design are resulting
  in injuries on a regular basis!!!

The problem is, sometimes people don't stop. Sometimes they
simply assume that the light will be green because
stopping under a bridge does not feel normal. Of course
they must accept the blame for not being more alert,
however, at what point does the fallibility of humans excuse
poor interface design?

Humans are by nature INCAPABLE of maintaining perfect
alertness, and driving requires more processing than the
human mind can possibly muster. Your mind is constantly
attempting to predict the future outcome of current
events, and it is this unconsciousness mechanism that, when
overloaded, will force the less acute modality of intuition
to propagate up and take full control.

It is for that very reason that we must design interfaces
with the fallibility of human operators in mind -- at least
until we can remove the human from the equation.

We MUST strive to achieve the highest level of
intuitiveness whilst eliminating any and all inconsistencies
from the system.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: GUI:-please answer want to learn GUI programming in python , how should i proceed.

2013-12-16 Thread Rick Johnson
On Sunday, December 15, 2013 11:01:53 AM UTC-6, Steven D'Aprano wrote:
 On Sun, 15 Dec 2013 14:53:45 +, Grant Edwards wrote:
  On 2013-12-14, Steven D'Aprano wrote:
 
  You seem to be equating was compiled from with includes an
  implemenation of.  Do you say that CPython ships with C?

 Well, when you take my comments out of their context, that
 does seem to be a totally stupid thing to say. But in
 context, it's only *mostly* stupid, and mostly stupid
 means a little bit sensible *wink* The context was a
 complaint, or at least expression of surprise, that Python
 use Tcl for a GUI, this being contrasted with
 (paraphrasing the legions of people who have expressed
 surprise about this in the past) some hypothetical GUI
 written in Python. But in practice, it won't be written
 in Python, it will be likely written in C or some other
 low-level language with some interface to Python. The main
 difference between this hypothetical Python GUI and Tcl
 is that Tcl is a Turing-complete interpreter which lives
 in it's own process.

And how many times would you take advantage of that turning
complete functionality in reality? My answer... ZERO! How
many Tcl calls have you, or anybody, made that did have
direct business with creating or managing a TK gui? HOW
MANY???

We don't need that functionality, we ALREADY have a
language... it's called Python and the syntax is MUCH
better. All we want is a damn GUI.

And trying to justify TCL as legit because Tcl just calls C
routines is ludicrous. If the intention is to extend C
routines, then by gawd EXTEND them. Don't go writing a whole
new turning complete monstrosity and forcing all calls to
travel through it's front door, sit in waiting room until
it's eyes bleed, before finally exiting out the back door on
it's way to Cees-ville.

Why should i give a damn about Tcl? All it does is get in my
way. OTOH, if Tcl where more like a Vegas Casino for high
rollers, i might be inclined to overlook the superfluous
pit-stop. A free luxury room , free all you can eat buffet,
free call girls, etc... but it has no endearing qualities.


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


Re: New to Python, Help to get script working?

2013-12-17 Thread Rick Johnson
On Monday, December 16, 2013 1:09:38 AM UTC-6, Mark wrote:
 On Sunday, December 15, 2013 9:33:17 PM UTC-5, Chris Angelico wrote:
  I went and looked at the post linked to, and it has
  buggy indentation. (Quite possibly indicates that the
  author has two-space tabs, and didn't notice a bug
  slipping in. I dunno.) Along the way, though, I learned
  that the script in question is entirely for generating
  fake twitch.tv viewers so as to get your stream
  highlighted fraudulently, so I'm rather less inclined to
  help. Got a legitimate use for this, or are you just
  trying to cheat your way to fame?
  
 Thanks for the reply, the answer is yes and no, i already
 have about 2400 followers and half mil views, i just
 wanted to see if i could get it to work.

That's like a serial spammer saying I already have 2400
spam bots and half a million victims but i just want to get
my latest bot working for academic purposes only. *wink*

Listen Mark, it's obvious you don't have any coding or
debugging skills and all you want to do is employ this app
for your own fraudulent purposes, so with that in mind:

NO SOUP FOR YOU!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: cascading python executions only if return code is 0

2013-12-22 Thread Rick Johnson
On Sunday, December 22, 2013 12:37:04 PM UTC-6, Frank Cui wrote:
 I have a requirement where I need to sequentially execute
 a bunch of executions, each execution has a return code.
 the followed executions should only be executed if the
 return code is 0. is there a cleaner or more pythonic way
 to do this other than the following ?

 if a() == 0:
 if b() == 0:
 c()

Hello Frank.

I kindly request that you be more specific when asking
questions. Both your question and your example code contain
too many ambiguities.

I'm still not sure what exact outcome you wish to achieve,
the only certainty is that you wish to perform a linear
execution of N members with later executions being affected
by earlier executions.

Whether you want executions to proceed on failure or proceed
on success is unclear. Here are a few explicit pseudo code
examples that would have removed all ambiguities:

if fails(a()):
if fails(b()):
c()

if succeeds(a()):
if succeeds(b()):
c()

Or if you prefer a purely OOP approach:

a.foo()
b.foo()
if a.failed:
if b.failed:
c.foo()

a.foo()
b.foo()
if a.succeeded:
if b.succeeded:
c.foo()

or you could simplify using a logical one liner:

if !a() and !b() then c()
if a() and b() then c()

Of course you could use the all function

if all(a(), b()):
c()
if not any(a(), b()):
c()

But this all depends whether you're testing for success or
testing for failure, and that point is a distant third from
my desperate need of understanding your semantics of what
values are *true* and what values are *false*.

I think (sadly) more time is spent attempting to interpret
what an OP is asking rather than attempting to provide a
solution to the problem the OP is suffering, and whilst any
problem solving adventure is likely to improve our
intelligence, fumbling about attempting to decode
ambiguities is indeed time that could have been better spent
IF ONLY the speaker (or writer) had put a small bit more
effort into the question.

Look Frank, nobody is perfect, we all need to improve our
skills here or there. So don't be offended that my
statements are, well,... frank.


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


Re: How can i return more than one value from a function to more than one variable

2013-12-23 Thread Rick Johnson
On Sunday, December 22, 2013 4:54:46 PM UTC-6, dec...@msn.com wrote:
 basically what I wanna do is this :
 x = 4
 
 y = 7
 def switch (z,w):
 ***this will switch z to w and vice verca***
  c= z
  z=w
  w=c
  print 'Now x =', w, 'and y = ' , z
  return w
 x = switch(x,y)

If your intent is to swap the values of two variables (which
is really rebinding the names only) then why do you need a
function at all when you could explicitly swap the values
yourself? What gain would a function give you -- even if you
could do it?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: cascading python executions only if return code is 0

2013-12-23 Thread Rick Johnson
On Sunday, December 22, 2013 5:02:51 PM UTC-6, Mark Lawrence wrote:
 On 22/12/2013 22:51, Chris Angelico wrote:

 if a() == 0:

  if b() == 0:

  c()

 I can only see one way that you can possibly intepret it.

Hmm, I guess i should not assume color vision to be ubiquitous.

 [snip]

The level of abstraction of that code sample is so high that
no one should assume anything from reading it. The only fact
we CAN be sure of is that IF a() equals 0 and b() equals 0
then c will execute. But that fact gives us no insight into
Frank's *real* source code, not to mention his mind.

Sure. We always want folks to trim example code to it's most
relevant parts before presenting the code on this list, but
just as ten thousands lines of code is useless, so too is 4
lines. It's not the number of lines that matter so much as
the context those line provide to the problem at hand.

If you take the small code example literally, then why does
Frank even need to ask a question about what will happen
when he could simply run the code and observe the results.

Here is the most simplified example of Franks code:

if 0 == 0:
if 0 == 0:
do_something()

This code is so *confined* as to be useless for
generalities. In fact, the only reason to ask a question
about such simplified code is to understand the execution
rules OR syntax of Python source code. Here are some
concrete facts about those three lines:

1. test one will ALWAYS eval true, and proceed to test two

2. test two will ALWAYS eval true, then execute do_something

3. what happens after that is undefined

These are fundamental behaviors of Python conditionals,
operators, callables, etc... which we *already* understand
quite completely. But these fundamentals will not help us
understand Frank's problem.

What we need is help Frank is *CONTEXT*.

Now, even though Frank's code offers a small increment in
complexity over my simplified form, it offers *zero*
context of that complexity:

1. test one will evaluate true or false, then proceed (or
not, depending on the return value of a) to test two

2. test two will evaluate true or false, then proceed (or
not, depending on the return value of b) to execute the
body

3. What happens in a, b, and c is undefined.

The problem is we have no idea what happens in a,b,and c...
but those facts may not matter, what does matter is what a
return value of zero *means* to Frank, and without an
understanding of these Frank semantics, how could we
possibly extrapolate a solution to such ambiguous questions?

You see, there exist no rules in Python for what a return
value of 0 should mean. Should it mean success? Should it
mean failure? Should it mean eat pasta quickly? Well it
could mean all those things to different people.

Since function return values are defined by programmers,
*ONLY* the programmer himself-- or those familiar with the
entire code base --can resolve the ambiguities with any
degree of precision.

Even IF you are presented with a small snippet of code that
include the identifier for the return value, you still
cannot be certain that extrapolating meaning from an
identifier *alone* will give you the insight to remove all
ambiguity.

For example, let's say the return value is proceed and
attached to name spelled flag. Do you really think you can
extrapolate the purpose of that value being returned?

proceed with what?

Proceed counting unicorns?
Proceed raising exceptions?
Proceed extrapolating to infinity and beyond?!

You can guess, but that is all. Which brings us full circle
to the problem at hand.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Recovering deleted files

2013-12-26 Thread Rick Johnson
On Wednesday, December 25, 2013 10:44:39 PM UTC-6, George Tang wrote:
 I am new to python and was trying to program with txt
 files, and tried to move the txt file to a new directory.
 i did not read very carefully about what shutil.move(src,
 dst) does and it deleted some of my files. How do i
 recover my lost files. plz help!

Well George that's unfortunate. 

I hate to say i told you so, but i've been preaching the
importance of testing code that manipulates files for many
years. If only you had run the code a few times and MERELY
printed the src and dst paths to stdout you MIGHT could have
saved yourself a tough lesson.

But all may not be lost. 

If you want to post the relevant bits of the source code we
may find a solution for you. Maybe your path munging was
clumsy and you moved them somewhere unexpected... who
knows???
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: On a scrollbar for tkinter

2014-01-02 Thread Rick Johnson
I know you're using Python3.x, so there may be new functionality in Tkinter 
that i am not aware of yet. I still have oodles of Python2.x dependencies and 
really don't see a need to make the jump yet -- so keep that in mind when 
taking my advice below. 

In the old days of Tkinter, if you wanted to scroll the mainframe (aka:root, 
aka:Tkinter.Tk) you had two choices:

OPTION_1. Use tk.Canvas and create_window method
http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/create_window.html

OPTION_2. The TIX extension widgets for Tkinter has a scrolledwindow object 
that requires much less work and provides a more intuitive interface than the 
canvas.

PS: It's Terry not Teddy.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Tkinter GUI Error

2014-01-13 Thread Rick Johnson
On Monday, January 13, 2014 12:49:07 PM UTC-6, Lewis Wood wrote:
 labelent1 = Label(main, text=Correct!,fg=green).grid(row = 0, column = 3)
 
 [snip]
 
 UnboundLocalError: local variable 'labelent1' referenced before assignment

Observe the following interactive session and prepare to be enlightened.

## INCORRECT ##
py from Tkinter import *
py root = Tk()
py label = Label(root, text=Blah).pack()
py type(label)
type 'NoneType'

## CORRECT ##
py label = Label(root, text=Blah)
py label.pack()
py label
Tkinter.Label instance at 0x027C69B8
py type(label)
type 'instance'

## ANY QUESTIONS? ##
py help()
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: buggy python interpretter or am I missing something here?

2014-01-27 Thread Rick Johnson
On Monday, January 27, 2014 3:32:43 AM UTC-6, me wrote:
 On Mon, 27 Jan 2014 20:01:33 +1100, Chris Angelico wrote:
 
 [snip chris reply]
 
 You feel better now that you too have vented?  I had a
 productive discussion with a couple of top level posters
 who helped me solve my problem and they receive
 appropriate kuddos.  Now it seems that some lonely
 individuals who maybe just want some attention are coming
 out of the woodwork.

You can kindly ignore Chris, he is just one of our well
known *resident* lonely individuals, seeking attention yet
again! And his constant blabbing about and idol worship of REXX is
more annoying than all of xah lee post combined, however, i
do just enjoy watching him casually weaving in those
examples as though he does not have an agenda to push.

@Chris: Two can play at this game!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: buggy python interpretter or am I missing something here?

2014-01-27 Thread Rick Johnson
On Monday, January 27, 2014 9:53:37 AM UTC-6, Chris Angelico wrote:
 Heh. If you'd said Pike instead of REXX, I might have
 believed you :) I've said more about Pike than is perhaps
 appropriate, but of late, I've actually not been the one
 to most often quote REXX code.

Yes in my haste to inject a jab at you i pulled the
trigger before fully retracting the gun from my holster...
OUCH!

It was indeed Pike that i meant. But, although you
*do* mention it quite a lot, i don't think mentioning any
language should be off topic because heck, someone could
learn something new.

 [snip]
 For instance, I personally believe that disallowing
 assignment-as-expression cuts out more value than it gains
 by preventing bugs (as we've seen lately, people can just
 get it wrong the other way, comparing as a statement),

I myself wish for such a Python feature -- but alas, we are but
slaves to whims of the dutch!

 but I respect Guido's decision on that and don't see it as
 a problem to be fought. A lot of Python's worst flaws were
 fixed in 3.x (input() - eval(), print as a statement,
 etc),

I agree that those are flaws, but not enough of a flaw to
break code. input is only used by neophytes, so who cares
about breaking that one, but print is almost everywhere!

But let's go back to input for a bit...

Why do we even need an input function anyway if all
it is going to do is read from stdin? Would not $stdin.read
have been better choice? Or simply read if you're a global
namespace pollution fanboy!

Heck, if you're going to have a function for writing
strings to $stdout, and also, you're going to have a
function for reading strings from $stdin, then you need to
recognize the diametric relation between these functions,
and as such, your first design consideration should be to
maintain a consistency between them

input (reads a string from stdin)
print (writes a string to stdout)

It is my strong believe that defining an input method that
magically evals the input string is just plain evil. Why
you ask? Because doing so injects superfluous magic whist
simultaneously blinding the noob to the fact that strings
are the mutually inclusive love interest of both Mrs.Input
and Mr.Output.

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


PyWart: More surpises via implict conversion to boolean (and other steaming piles!)

2014-02-10 Thread Rick Johnson
## START CODE ###
def foo():
# foo represents a patternless function
# or method that returns a Boolean value
# based on some internal test.
#
if 1==1:
return True
return False
#
# The fun begins when two tiny chars are forgotten,
# however, since the code is legal, python will happily
# give us the wrong answer.
#
if foo: # - forgot parenthesis!
print 'implicit conversion to bool bites!'
else:
#
# This block will NEVER execute because foo is
# ALWAYS True!
#
#
# Some introspection to understand why this happened.
#
print 'foo =', foo
print 'bool(foo) -', bool(foo)
#
## END CODE #

It's obvious i did not follow the syntactical rules of
Python, i understand that, however, there are three design
flaws here that are contributing to this dilemma:

1. Implicit conversion to Boolean is evil

2. Conditionals should never accept parameter-less
functions. If you want to check if a callable is
True or False, then use if bool(callable). Any
usage of a bare callable in conditionals should
raise SyntaxError.

3. Implicit introspection is evil, i prefer all
references to a callable's names to result in a CALL
to that callable, not an introspection!
Introspection should ALWAYS be explicit!

For a long time i thought Python's idea of a returning the
value of a callable-- who's name is unadorned with (...)
--was a good idea, however, i am now wholly convinced that
this design is folly, and the reason is two fold:

1. Parenthesis should not be required for parameter-
less functions. I realize this is a bit more
complicated in languages like Python where
attributes are exposed to the public, but still, not
reason enough to require such onerous typing.

2. Implicit introspection is evil. I would prefer an
explicit method attached to all callables over a
sugar for callable.call. We should never consume
syntactical sugars UNLESS they can greatly reduce
the density of code (like math operators for
instance!)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Import order question

2014-02-18 Thread Rick Johnson
On Monday, February 17, 2014 1:40:41 PM UTC-6, Ben Finney wrote:
 Nagy László Zsolt ... writes:
   Use modules to group your class definitions conceptually. There is
   no need whatever to separate every class into a different module.
  If there is a consensus, and it is really desireable to put all these
  related classes into the same module, then this is what I'm going to
  do.

It is not desirable to me, and i would argue truthfully,
to many others either.

 You should use multiple modules to separate the code where it makes
 sense, along *conceptual* lines. Make separate modules that each
 represent a conceptually-separate area of functionality in your
 application, and put the classes which implement that functionality in
 that module.

Classes with an s? As in many classes in one source file?
Are you insane man? Why oh why would you torture yourself
and others with such advice? Are you some sort of hard disc
neat freak? Do you fear cluttering your hard-drive with too
many files will overwork it? What of yourself?

I'm continually amazed by you Java haters who will
willingly place burdens on yourself just to spite that mean
old Java. Splitting code into small source files is wise,
whereas, creating single monolithic monstrosities like
Tkinter should be a sin! A sin that should be punishable by
the Exception!

As the lines of code increase, so does the complexity of
navigating and maintaining large modules. Classes should
naturally exist in their own module with the exception of
small utility or special use classes that are not exposed
publicly.

Then you go and intermix the areas of module source code
and module API. These are two distinct areas that need not
follow the same patterns. You can have 20 classes contained
in 20 different source files and then combine them
transparently at run-time so that as far as the client is
concerned, all the classes exist under one namespace.

# ui_mod1.py
class One():pass

# ui_mod2.py
class Two():pass

# ui_mod3.py
class Three():pass

# ui_mod4.py
class Four():pass

# ui_main.py
from ui_mod1 import *
from ui_mod2 import *
from ui_mod3 import *
from ui_mod4 import *

At least by this method i can maintain the code base without
wearing-out my scroll finger and eventually loosing my mind.
THE MORAL: With very few exceptions, please put EVERY class
in it's own module.

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


Re: Bad Code Snippet of the Day

2014-02-18 Thread Rick Johnson
On Tuesday, February 18, 2014 10:47:15 AM UTC-6, Chris Angelico wrote:
 I call this Russian Exception Roulette. It came about because of
 some discussions on python-ideas regarding the new PEP 463 and
 exception handling.
 try:
 
 exc = getattr(__builtins__,random.choice(list(filter(lambda x:
 x.endswith(Error),dir(__builtins__)
 f()
 except exc:
 print(You win!)
 Given a function f(), defined elsewhere, what will this do?

For get about f(), it will throw a NameError since random 
was not imported. 

Beyond that this code (either conscientiously or unconsciously)
exposes the onerous and obfuscation of a language design
that coddles a global function nightmare paradigm over the
elegance of true OOP -- talk about cutting off your nose
just to spite your face!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Import order question

2014-02-18 Thread Rick Johnson
On Tuesday, February 18, 2014 3:02:26 PM UTC-6, Chris Angelico wrote:
 On Wed, Feb 19, 2014 at 7:41 AM, Rick Johnson wrote:
  # ui_main.py
  from ui_mod1 import *
  from ui_mod2 import *
  from ui_mod3 import *
  from ui_mod4 import *
  At least by this method i can maintain the code base without
  wearing-out my scroll finger and eventually loosing my mind.
  THE MORAL: With very few exceptions, please put EVERY class
  in it's own module.
 Absolutely definitely not. If you're going to import * into every
 module, just write it all in a single source file.

Writing multiple individual classes in multiple individual
modules, and then importing those individual classes under a
single namespace at run-time is key to exposing a monolithic
API to a client without storing all the source code in a
monolithic file. The Tkinter folks would be wise to follow
my advise!

But I'm not suggesting this is the solution to EVERY
problem, or even that this is the solution to the OP's
current problem, what i am suggesting is that source files
should be kept as short as possible so as to accommodate easy
maintenance.

You see, unlike other languages, Python does not give us a
choice of the start and end of a Python module, there is no
keyword or delimiting chars that we can use to EXPLICITLY
define the start and end of a Python module. No, EVERY
Python script IS a module by default, and that is the law of
the land.

 Otherwise, when
 someone tries to find the source code for some particular class or
 function, s/he has to go digging through all five source files - first
 the utterly useless merge-point, then the four others, because there's
 no way to know which one has it.

Only if you're blind, or your source code was written by
people lacking even a modicum of common sense about how to
name a module. Most modules can simply be the name of the
containing class. Heck, even an idiot can manage that!

 Python could make this easier for us, by retaining the origin of every
 function and class. And maybe it's already there, but I don't know
 about it.

Google inspect and be enlightened. But Chris, if you have
to use the inspect module to find a class then sir, you need
lack: simple search tools, and/or motivation.

Are you telling me you're willing to search through a single
file containing 3,734 lines of code (yes, Tkinter) looking
for a method named destroy of a class named OptionMenu
(of which three other classes contain a method of the same
exact name!), when all you needed to do was open one single
module named tk_optionmenu.py and do a single search for
def destroy?

You must be trolling!

 But even if it did exist (by the way, it would be useful for
 other things than just taming a mad layout like this), it'd still be
 better to keep everything combined, because the origin of a
 function/class could just as easily go to the exact line as to the
 file.
 A module is a namespace. It should be used as such. If you want a
 package, use a package. There's no point putting each class out
 separate unless you really need that.

But in many cases you do! Chris, i think you missed the
entire crux of this thread. The OP is not writing a single
monolithic program where the code will ONLY be investigated
by the developers, no, he's creating an API, and API's
require structure.

But even if this were not an API, breaking large chunks of
code up and spreading them across individual files is the
key to managing code bases.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Import order question

2014-02-18 Thread Rick Johnson
On Tuesday, February 18, 2014 4:17:48 PM UTC-6, Tim Chase wrote:
 On 2014-02-19 08:49, Chris Angelico wrote:
  At my last job, I had a single C++ file of roughly 5K lines, and
  it wasn't at all unmanageable. Probably wouldn't have been a
  problem to have another order of magnitude on that. What sort of
  wimpy text editor are you using that you can't find what you're
  looking for in a single large file?
 Even the venerable ed handles files of those sizes without batting
 an eye.  I just opened a 2MB XML file (50k lines) in ed and jumped
 all around in it with no trouble at all.  It's as simple as
   1;/class OptionMenu/;/def destroy/
 in most cases.  If your editor can't help you do simple things like
 that, I recommend you find an editor that is at least as good as
 ed. :-)

SarcasticSam: Who needs directories anyway when the
hard-drive is already one gigantic directory... THOSE IDIOTS!

Yes Sam, it seems this thread has degenerated into a testosterone
induced contest to determine who can open the largest file,
climb inside, and then jump around the fastest -- MAY THE
BEST MEAT-HEAD WIN!

For the rest of us --of which who respect brains over
brawn-- we'll swallow our foolish pride and wield the
technology of sane structures.

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


Re: Import order question

2014-02-18 Thread Rick Johnson
On Tuesday, February 18, 2014 5:28:21 PM UTC-6, Rotwang wrote:
 I have music software that's a single 9K-line Python module, which I 
 edit using Notepad++ or gedit. If I wish to find e.g. the method edit 
 of class sequence I can type
  Ctrl-fclass seqReturndef edit(Return

This is not about how to use a search function[1], because
even modules that contain ONLY *one* class can be many
hundreds or even thousands of lines, thereby demanding the
use of search functions/dialogs. 

Heck, when a class gets too big i even export some of the
methods to outside modules and load the methods dynamically
at run-time just to cut down on the length. I suppose my
detractors would find that surprising also!

[1] Red Herring, Red Herring!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Nexus Programming Language

2012-06-10 Thread Rick Johnson
On Jun 10, 7:21 am, Colin J. Williams c...@ncf.ca wrote:
 On 10/06/2012 1:45 AM, rusi wrote:
  What does nexus have that python doesn't?
  Yeah I know this kind of question leads to flames but a brief glance
  at the about page does not tell me anything in this direction.

 It has a more complex block structure, with lots of braces {}.

So in other words, it another Ruby?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nexus Programming Language

2012-06-10 Thread Rick Johnson
On Jun 10, 12:45 am, rusi rustompm...@gmail.com wrote:
 On Jun 10, 7:46 am, Adam Campbell abcampbell...@gmail.com wrote:

  The Nexus programming language version 0.5.0 has been released. It is
  an object-oriented, dynamically-typed, reflective programming
  language, drawing from Lua and Ruby.www.nexuslang.org

 What does nexus have that python doesn't?
 Yeah I know this kind of question leads to flames but a brief glance
 at the about page does not tell me anything in this direction.

Oh rusi, you're not fooling anybody. We know your a total ruby fanboy
and probably an unoffical member of the nexus dev team.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what gui designer is everyone using

2012-06-10 Thread Rick Johnson
On Jun 7, 4:18 pm, Kevin Walzer k...@codebykevin.com wrote:
 On 6/5/12 10:10 AM, Mark R Rivet wrote:

  I want a gui designer that writes the gui code for me. I don't want to
  write gui code. what is the gui designer that is most popular?

 None. I write GUI code by hand (Tkinter).

I second that notion. Writing GUI code by hand is the only way.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic cross-platform GUI desingers à la Interface Builder (Re: what gui designer is everyone using)

2012-06-10 Thread Rick Johnson
On Jun 8, 7:27 am, Wolfgang Keller felip...@gmx.net wrote:

 This whole cycle of design GUI-generate code-add own code to
 generated code-run application with GUI has always seemed very
 un-pythonic to me. A dynamic, interpreted language should allow to work
 in a more lively, direct way to build a GUI.

I strongly agree with this statement also.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic cross-platform GUI desingers à la Interface Builder (Re: what gui designer is everyone using)

2012-06-10 Thread Rick Johnson
On Jun 9, 8:25 am, Dietmar Schwertberger n...@schwertberger.de
wrote:

 Before anyone now writes Good GUIs are coded by hand:
 I agree, but for many purposes only simple GUIs are required
 and it should be possible to create these without studying manuals
 (on toolkit and GUI editor).

It is possible. Try Tkinter for the get-you-from-a-to-b solution,
or, wxPython if you like fog lamps, heated seats, and navigation
systems.

 A typical simple GUI would e.g. be for a measurement / data aquisition
 program, where you just need some buttons and fields.

Buttons and feilds are just a few short lines of code. Look. You guys
don't need a visual GUI builder. What you need to do is stop being
lazy and spend a few hours studing the basics of Tkinter and wxPyhon
(or whatever else suits your needs). IMO, every single python
programmer who needs GUI interfaces should know the basics of AT LEAST
Tkinter without even looking at the docs. I mean, how difficult is:

import Tkinter as tk
from Tkconstants import *
root = tk.Tk()
root.title('Noob')
for x in range(10):
f = tk.Frame(root)
f.pack(fill=X, expand=YES)
l = tk.Label(f, text=Field_+str(x))
l.pack(side=LEFT, anchor=W)
e = tk.Entry(f)
e.pack(side=LEFT, fill=X, expand=YES)
root.mainloop()
#
# Or even better. Use grid!
#
root = tk.Tk()
root.title('Amatuer')
root.columnconfigure(1, weight=1)
for x in range(10):
l = tk.Label(root, text=Field_+str(x))
l.grid(row=x, column=0, sticky=W)
e = tk.Entry(root)
e.grid(row=x, column=1, sticky=W+E)
root.mainloop()
#
# Or become a pro and create reusable objects!
#
class LE(tk.Frame):
def __init__(self, master, **kw):
tk.Frame.__init__(self, master)
self.l = tk.Label(self, **kw)
self.l.pack(side=LEFT)
self.e = tk.Entry(self)
self.e.pack(side=LEFT, fill=X, expand=YES)
root = tk.Tk()
root.title('Pro')
for x in range(10):
le = LE(root, text=Field_+str(x))
le.pack(fill=X, expand=YES)
root.mainloop()



 I think that something in the style of Visual BASIC (version 6) is required
 for either wxPython or PyQt/PySide (or both).
 In the Visual BASIC editor you can e.g. add a GUI element
 and directly go to the code editor to fill methods (e.g. an OnClick
 method).

With Tkinter you add a GUI element IN THE CODE and then you are
ALREADY in the code editor! What an amazing concept! No juggling
editors and windows. No need to mentally switch from one language to
another. Can you imagine how productive you could be?

 If you have not used VB before, you should just try it. You can create
 GUIs within a few minutes even if you haven't used it before.

Allow me to qualify that very naive generalization: ANYBODY and point
and click, very few can actually write code.

 (Sure, the fact that anyone can use it has the side effect that most
   of these GUIs are not good...)

Well i see that you agree. Look. This is fact. GUI's require you to
write code. You cannot get around this fact. Sure, you can create some
templates. But in the end, you will have to write in order to link the
templates together.

I say. If your GUI kit gives you the feeling that you are writing too
much boilerplate, well, then, it's time to wrap up some re-usable
functionality on your own. I have done this myself with Tkinter AND Wx.
( although much more so with Tkinter being that is a poorly designed
GUI)

 Also:
 Such an editor should support simple manual layouts without enforcing
 the use of sizers (wx) or layout managers (Qt).
 These add an additional level of complexity which is not required
 for simple GUIs.

See above code for example of *gasps* simple layouts in REAL code!

 Background:
 I'm using Python in a corporate environment but I'm more or less
 the only one using it. I could propagate Python for wider use as it
 is the best available language for things like hardware control and
 data acquisition, but the lack of an easy-to-use GUI editor is
 the blocking point.

BS!

 I can teach anyone how to create a program for data
 acquisition, but I don't see how more than a few could create a GUI
 without an easy-to-use tool.

Like Tkinter?

 There's still a lot of VB6 code around as there's no replacement and
 this gap could well be filled by Python.

Visual Basic sucks. I spend more time re-focusing my mental energy
than actually getting work done. There is no replacement for pure raw
code. You visualize GUI's in you mind, and fingers bring that vision
to life through properly written API's.

Never invent a new problem for a solution that does not exist.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic cross-platform GUI desingers à la Interface Builder (Re: what gui designer is everyone using)

2012-06-10 Thread Rick Johnson
On Jun 10, 2:36 pm, Rick Johnson rantingrickjohn...@gmail.com wrote:

 #
 # Or become a pro and create reusable objects!
 #
 class LE(tk.Frame):
     def __init__(self, master, **kw):
         tk.Frame.__init__(self, master)
         self.l = tk.Label(self, **kw)
         self.l.pack(side=LEFT)
         self.e = tk.Entry(self)
         self.e.pack(side=LEFT, fill=X, expand=YES)
 root = tk.Tk()
 root.title('Pro')
 for x in range(10):
     le = LE(root, text=Field_+str(x))
     le.pack(fill=X, expand=YES)
 root.mainloop()

PS: The keywords argument should have been passed to the entry widget
and NOT the label. Yes, occasionally, even pros make subtle mistakes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Passing ints to a function

2012-06-10 Thread Rick Johnson
On Jun 9, 3:29 am, Jussi Piitulainen jpiit...@ling.helsinki.fi
wrote:

 Here's something you could have thought of for yourself even when you
 didn't remember that Python does have special built-in support for
 applying a function to a list of arguments:

 def five(func, args):
    a, b, c, d, e = args
    return func(a, b, c, d, e)


 The point is that the function itself can be passed as an argument to
 the auxiliary function that extracts the individual arguments from the
 list.

Good point. However the function five is much too narrowly defined
and the name is atrocious! I like concise, self-documenting
identifiers.

py L5 = [1, 2, 3, 4, 5]
py L4 = [1, 2, 3, 4]
py def f4(a,b,c,d):
print a,b,c,d
py def f5(a,b,c,d,e):
print a,b,c,d,e
py def apply_five(func, args):
a, b, c, d, e = args
return func(a, b, c, d, e)
py apply_five(f5, L5)
1 2 3 4 5
py apply_five(f5, L4)
ValueError: need more than 4 values to unpack
#
# Try this instead:
#
py def apply_arglst(func, arglst):
return func(*arglst)
py apply_arglst(f4,L4)
1 2 3 4
py apply_arglst(f5,L5)
1 2 3 4 5

...of course you could create a general purpose apply function; like
the one Python does not possess any longer ;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic cross-platform GUI desingers à la Interface Builder (Re: what gui designer is everyone using)

2012-06-11 Thread Rick Johnson
On Jun 10, 11:05 pm, rusi rustompm...@gmail.com wrote:

 If python is really a language maven's language then it does not do
 very well:
 - its not as object-oriented as Ruby (or other arcana like Eiffel)
if it were object-oreiented as Ruby, then why not use Ruby?

 - its not as functional as Haskell
if it were as functional as Haskell, then why not use Haskell?

 - its not as integrable as Lua
if it were as integrable as Lua, then why not use Lua?

 - its not as close-to-bare-metal as C
if it were as asinine as C, then why not use C?

 - etc
exactly!

 Then why is it up-there among our most popular languages? Because of
 the 'batteries included.'

No. It's up there because it does not FORCE you to program in a single
paradigm. Look. I love OOP. It works well for so many problems -- but
not for ALL problems! I like the freedom i have when using Python. I
don't get that feeling anywhere else.

 And not having a good gui-builder is a battery (cell?) that is
 lacking.

Nonsense. I'm not saying we should NEVER have a visual gui builder,
no,  but i am saying that we don't need one to be a great language.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic cross-platform GUI desingers à la Interface Builder (Re: what gui designer is everyone using)

2012-06-11 Thread Rick Johnson
On Jun 11, 9:09 am, Mark Roseman m...@markroseman.com wrote:

 Second, there does exist at least one fairly good source of
 documentation for new users wishing to do exactly this (according to
 many, many comments I have received), though that documentation is
 admittedly buried in a sea of out-of-date information that is still all
 too easy to find.

Well you Mark you have really hit it this time.

 * Outdated tuts are contributing to the slow adoption of Python3000
 * Outdated tuts are contributing the animosity towards Tkinter.
 * Poorly written tuts are doing even more damage.

I have pointed this out before with very little feedback from our
community members. So you know what i did... about two years ago i
start a quest to rid the WWW of old and outdated tutorials. I send out
email after email; begging; pleading, and yes even brown-nosing!...
and you know how many reposes i got? Three! Yes three! And one of the
three told me to eef-off.

The other two chaps not only updated their tutorials, they even sent
me a nice Thank you letter. Oh. And the one who told me to eff-off, he
re-read my email and decided he took it out of context and then he
updated his tut also.

You see. If I, or me rather, the despised and hated rantingrick
can inspire three people to contribute positively to this community,
well, just imagine what you or *gasps* GvR could do! Is any heavy
weight willing to step forward and be heard? What say you? The silence
is deafening.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question:Programming a game grid ...

2012-06-27 Thread Rick Johnson
On Jun 27, 5:21 pm, iconoclast011 iconoclast...@gmail.com wrote:
 Fairly new to Python ... Is there a way to efficiently (different from my 
 brute
 force code shown below) to set up a game grid of buttons (ie with pygame)
 responding to mouse clicks ?   I would want to vary the size of the grid ...

 Thanks

 Brute force code:
 from Tkinter import *

 root = Tk()

 f = Frame(root, bg = blue, width = 500, height = 500)
 f.pack(side=LEFT, expand = 1)

 f3 = Frame(f, bg = white, width = 500)
 f3.pack(side=LEFT, expand = 1, pady = 50, padx = 50)

 #f2 = Frame(root, bg = black, height=100, width = 100)
 #f2.pack(side=LEFT, fill = Y)

 #b = Button(f2, text = test)
 #b.pack()

 var = 'b00'
 vars()[var] = Button(f3, text = 00, bg = white)
 b00.grid(row=0, column=0)
 b00.bind('Button-1', leftclick)   # bind left mouse click
 b00.bind('Button-3', rightclick)   # bind left mouse click

 var = 'b01'
 vars()[var] = Button(f3, text = 01, bg = white)
 b01.grid(row=0, column=1)
 b01.bind('Button-1', leftclick)   # bind left mouse click
 b01.bind('Button-3', rightclick)   # bind left mouse click

 b02 = Button(f3, text = 02, bg = white)
 b02.grid(row=0, column=2)
 b02.bind('Button-1', leftclick)   # bind left mouse click
 b02.bind('Button-3', rightclick)   # bind left mouse click

 b03 = Button(f3, text = 03, bg = white)
 b03.grid(row=0, column=3)
 b03.bind('Button-1', leftclick)   # bind left mouse click
 b03.bind('Button-3', rightclick)   # bind left mouse click

 b04 = Button(f3, text = 04, bg = white)
 b04.grid(row=0, column=4)
 b04.bind('Button-1', leftclick)   # bind left mouse click
 b04.bind('Button-3', rightclick)   # bind left mouse click

 b05 = Button(f3, text = 05, bg = white)
 b05.grid(row=0, column=5)
 b05.bind('Button-1', leftclick)   # bind left mouse click
 b05.bind('Button-3', rightclick)   # bind left mouse click

 b06 = Button(f3, text = 06, bg = white)
 b06.grid(row=0, column=6)
 b07 = Button(f3, text = 07, bg = white)
 b07.grid(row=0, column=7)
 b08 = Button(f3, text = 08, bg = white)
 b08.grid(row=0, column=8)

 b10 = Button(f3, text = 10, bg = white)
 b10.grid(row=1, column=0)
 b11 = Button(f3, text = 11, bg = white)
 b11.grid(row=1, column=1)
 b12 = Button(f3, text = 12, bg = white)
 b12.grid(row=1, column=2)

 b13 = Button(f3, text = 13, bg = white)
 b13.grid(row=1, column=3)
 b14 = Button(f3, text = 14, bg = white)
 b14.grid(row=1, column=4)
 b15 = Button(f3, text = 15, bg = white)
 b15.grid(row=1, column=5)

 b16 = Button(f3, text = 16, bg = white)
 b16.grid(row=1, column=6)
 b17 = Button(f3, text = 17, bg = white)
 b17.grid(row=1, column=7)
 b18 = Button(f3, text = 18, bg = white)
 b18.grid(row=1, column=8)

 b20 = Button(f3, text = 20, bg = white)
 b20.grid(row=2, column=0)
 b21 = Button(f3, text = 21, bg = white)
 b21.grid(row=2, column=1)
 b22 = Button(f3, text = 22, bg = white)
 b22.grid(row=2, column=2)

 b23 = Button(f3, text = 23, bg = white)
 b23.grid(row=2, column=3)
 b24 = Button(f3, text = 24, bg = white)
 b24.grid(row=2, column=4)
 b25 = Button(f3, text = 25, bg = white)
 b25.grid(row=2, column=5)

 b26 = Button(f3, text = 26, bg = white)
 b26.grid(row=2, column=6)
 b27 = Button(f3, text = 27, bg = white)
 b27.grid(row=2, column=7)
 b28 = Button(f3, text = 28, bg = white)
 b28.grid(row=2, column=8)

 b30 = Button(f3, text = 30, bg = white)
 b30.grid(row=3, column=0)
 b31 = Button(f3, text = 31, bg = white)
 b31.grid(row=3, column=1)
 b32 = Button(f3, text = 32, bg = white)
 b32.grid(row=3, column=2)

 b36 = Button(f3, text = 36, bg = white)
 b36.grid(row=3, column=6)
 b37 = Button(f3, text = 37, bg = white)
 b37.grid(row=3, column=7)
 b38 = Button(f3, text = 38, bg = white)
 b38.grid(row=3, column=8)

 b33 = Button(f3, text = 33, bg = white)
 b33.grid(row=3, column=3)
 b34 = Button(f3, text = 34, bg = white)
 b34.grid(row=3, column=4)
 b35 = Button(f3, text = 35, bg = white)
 b35.grid(row=3, column=5)

 b40 = Button(f3, text = 40, bg = white)
 b40.grid(row=4, column=0)
 b41 = Button(f3, text = 41, bg = white)
 b41.grid(row=4, column=1)
 b42 = Button(f3, text = 42, bg = white)
 b42.grid(row=4, column=2)

 b43 = Button(f3, text = 43, bg = white)
 b43.grid(row=4, column=3)
 b44 = Button(f3, text = 44, bg = white)
 b44.grid(row=4, column=4)
 b45 = Button(f3, text = 45, bg = white)
 b45.grid(row=4, column=5)

 b46 = Button(f3, text = 46, bg = white)
 b46.grid(row=4, column=6)
 b47 = Button(f3, text = 47, bg = white)
 b47.grid(row=4, column=7)
 b48 = Button(f3, text = 48, bg = white)
 b48.grid(row=4, column=8)

 b50 = Button(f3, text = 50, bg = white)
 b50.grid(row=5, column=0)
 b51 = Button(f3, text = 51, bg = white)
 b51.grid(row=5, column=1)
 b52 = Button(f3, text = 52, bg = white)
 b52.grid(row=5, column=2)

 b53 = Button(f3, text = 53, bg = white)
 b53.grid(row=5, column=3)
 b54 = Button(f3, text = 54, bg = white)
 b54.grid(row=5, column=4)
 b55 = Button(f3, text = 55, bg = white)
 b55.grid(row=5, column=5)

 b56 = Button(f3, text = 56, bg = white)
 b56.grid(row=5, column=6)
 b57 

Re: code review

2012-07-02 Thread Rick Johnson
On Jul 2, 3:20 am, Chris Angelico ros...@gmail.com wrote:
 On Mon, Jul 2, 2012 at 6:11 PM, Steven D'Aprano

 steve+comp.lang.pyt...@pearwood.info wrote:
  c  first_word  second_word == third_word  x

  I'm sure I don't have to explain what that means -- that standard chained
  notation for comparisons is obvious and simple.

  In Python, you write it the normal way, as above. But some other
  languages force you into verbosity:

  (c  first_word) and (first_word  second_word) and (second_word ==
  third_word) and (third_word  x)

 Uhh, actually you DO have to explain that, because I interpreted it
 quite differently:

 ((c  first_word) and (first_word  second_word)) == (third_word  x)

Poor Chris. That's because you've been brainwashed into believing you
must spoon feed your interpreter to get your code working correctly.
Stop applying these naive assumptions to Python code. Python knows
when you reach the end of a statement, no need for redundant
semicolons! Python knows when its reached the end of block and needs
to drop back one level, no need for redundant road signs.  Python
knows Chris; Python KNOWS!

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


Re: code review

2012-07-02 Thread Rick Johnson
On Jun 30, 9:06 pm, Steven D'Aprano steve
+comp.lang.pyt...@pearwood.info wrote:
 On Sun, 01 Jul 2012 00:05:26 +0200, Thomas Jollans wrote:
  Yes. My sole point, really, is that normally, one would expect these
  two expressions to be equivalent:

  a  b  c
  (a  b)  c

 Good grief. Why would you expect that?

 You can't just arbitrarily stick parentheses around parts of expressions
 and expect the result to remain unchanged. Order of evaluation matters:

 2**3**4 != (2**3)**4

Yes but as Chris points out in the next message, you can inject the
following parenthesis without changing a thing!:

py 1 + 3 * 4
13
py 1 + (3 * 4)
13

Of course i understand the rules of operator precedence, however i
have never liked them AND i continue to believe that such
functionality breeds bugs and is in fact bad language design. I
believe all evaluations should be cumulative:

py 1 + 3 * 4
should ALWAYS equal 16!

With parenthesis only used for grouping:
py a + (b*c) + d

Which seems like the most consistent approach to me.

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


Re: code review

2012-07-02 Thread Rick Johnson
On Jul 2, 11:42 am, Chris Angelico ros...@gmail.com wrote:
 Rick, do you realize that you have
 to spoon-feed the interpreter with spaces/tabs when other interpreters
 just KNOW to drop back an indentation level when you close a brace?

Yes. And significant white space is my favorite attribute of Python
source code. But the difference here is like night and day. While your
getting bogged down playing match-the-brackets, i'm writing code and
being productive. I don't need to put any mental effort into pressing
the Enter+Tab keys. On the contrary, you must constantly break your
mental focus to corral the braces, and the sad part is, you're still
formatting your code like mine (with tabs and newlines!) however your
simultaneously juggling superfluously archaic syntax! Why Chris? WHY?

 I simply need to make sure that the interpreter and I have the same
 understanding of the code. It will then work correctly. There's
 nothing special about one syntax or another,

I agree in the sense of: to each his own. However. There are methods
of writing code that are more productive, and methods that are less
productive, and your emotive agenda of defending such nostalgic
pedantry is quite self-defeating.

 they're all just
 communication from my brain to a CPU, and different syntaxes are
 suited to different tasks. There's nothing inherently wrong with:

 right_length = len(x)  5,  20

Agreed. I wish we had one language. One which had syntactical
directives for scoping, blocks, assignments, etc, etc...

BLOCK_INDENT_MARKER - \t
BLOCK_DEDENT_MARKER - \n
STATEMENT_TERMINATOR - \n
ASSIGNMENT_OPERATOR - :=
CONDITIONAL_IF_SPELLING - IF
CONDITIONAL_ELSE_SPELLING - EL
...

 (I quite like braces, myself, [...] and only a relatively small
 amount of actual logic.

So you have a penchant for confinement and an aversion to logic? Hmm,
interesting!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: code review

2012-07-02 Thread Rick Johnson
On Jul 2, 2:06 pm, Thomas Jollans t...@jollybox.de wrote:
 On 07/02/2012 08:22 PM, Rick Johnson wrote:

  Agreed. I wish we had one language. One which had syntactical
  directives for scoping, blocks, assignments, etc, etc...

  BLOCK_INDENT_MARKER - \t
  BLOCK_DEDENT_MARKER - \n
  STATEMENT_TERMINATOR - \n
  ASSIGNMENT_OPERATOR - :=
  CONDITIONAL_IF_SPELLING - IF
  CONDITIONAL_ELSE_SPELLING - EL
  ...

 You must be joking.


Well i was slightly serious, but mostly sarcastic.

Whist customizable syntax would be a great benefit to the individual,
it would be a nightmare to the community -- the real solution lies in
assimilation!

I am reminded of a story: A few years back a very nice old woman
offered to give me her typewriter. She said: i might need to type a
letter one day and it would good to have around. It was a nice
typewriter for 1956, but she had no idea her little machine was
reduced to no less than a paper weight thanks to something called the
PC. Her machine had been extinct for decades. Effectually, SHE had
been extinct for decades.

When i hear people like Chris evangelizing about slavish syntax, i am
reminded of the nice old lady. Her intentions where virtuous, however
her logic was flawed. She is still clinging to old technology. Like
the Luddites she refuses to see the importance technological
advancements. And by harboring this nostalgia she is actually
undermining the future evolution of an entire species. Lifespans are
limited for a very important evolutionary reason!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: WxSlider Mouse Wheel Resolution

2012-07-02 Thread Rick Johnson
On Jul 2, 10:45 am, Wanderer wande...@dialup4less.com wrote:
 Is there a way to set the mouse wheel resolution for the wxPython
 wx.Slider? I would like to use the graphic slider for coarse control
 and the mouse wheel for fine control. Right now the mouse wheel makes
 the slider jump ten counts and I would like it to be a single count.

 Thanks

I have always found GUI mouse wheel events (and others) to be lacking
in the user tuned control category. NOTE: Instead of forcing your
lib users to configure specifics or re-bind events like(course,
medium, fine) simply pre-bind the following events and empower the end
user:

  MouseWheel - cb(MEDIUM)
  MouseWheel+ControlKey - cb(FINE)
  MouseWheel+ShiftKey - cb(COURSE)

What a novel FREAKING idea!

*school-bell-rings*

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


Re: WxSlider Mouse Wheel Resolution

2012-07-02 Thread Rick Johnson
On Jul 2, 3:45 pm, Rick Johnson rantingrickjohn...@gmail.com wrote:
 [...]
   MouseWheel - cb(MEDIUM)
   MouseWheel+ControlKey - cb(FINE)
   MouseWheel+ShiftKey - cb(COURSE)

Of course some could even argue that three levels of control are not
good enough; for which i wholeheartedly agree!

A REAL pro would provide a configurable method to the user for which a
slider (or numerical range) would pop up to micro-adjust the
increment. However! I think all widgets should expose every
configurable option to the end user. All configure options would be
available by default and the developer can restrict ANY configure
option(s) which would have disastrous side-effects for that particular
GUI.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Discussion on some Code Issues

2012-07-04 Thread Rick Johnson
On Jul 4, 6:21 pm, subhabangal...@gmail.com wrote:
 [...]
 To detect the document boundaries, I am splitting them into a bag
 of words and using a simple for loop as,

 for i in range(len(bag_words)):
         if bag_words[i]==$:
             print (bag_words[i],i)

Ignoring that you are attacking the problem incorrectly: that is very
poor method of splitting a string since especially the Python gods
have given you *power* over string objects. But you are going to have
an even greater problem if the string contains a $ char that you DID
NOT insert :-O. You'd be wise to use a sep that is not likely to be in
the file data. For example: SEP or SPLIT-HERE. But even that
approach is naive! Why not streamline the entire process and pass a
list of file paths to a custom parser object instead?

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


Re: simpler increment of time values?

2012-07-05 Thread Rick Johnson
On Jul 5, 10:19 am, Steven D'Aprano steve
+comp.lang.pyt...@pearwood.info wrote:
 The number of seconds in a day (true solar day) varies by between 13 and
 30 seconds depending on the time of the year and the position of the sun.

Indeed. Which proves that a time keeping system based on the haphazard
movements of celestial bodies is antiquated technology. Talk about job
security!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tkFileDialogs

2012-07-06 Thread Rick Johnson
On Jul 6, 12:22 am, brandon harris brandon.har...@reelfx.com wrote:
 [...]
 import tkFileDialog
 # Won't start in or allow navigation to APPDATA
 test = tkFileDialog.askdirectory(initialdir='%APPDATA%')
 # Will start in and navigate to APPDATA
 test = tkFileDialog.askopenfile(initialdir='%APPDATA%')

Don't you just love inconsistencies! I get weird results using your
string. Why not use expanduser?

py path = os.path.expanduser('~\\AppData')

Of course that will not solve your main problem though. Probably since
showing hidden files is a function of the OS setting, which explorer
follows blindly. I tried your code AFTER changing show
hidden_files_and_folders=True and both dialogs open into the correct
directory, as expected. You could modify the setting, then show the
dialog, then revert the setting back.

Ah. The joys of Win32 scripting... *chokes*
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simpler increment of time values?

2012-07-06 Thread Rick Johnson
On Jul 5, 12:16 pm, Chris Angelico ros...@gmail.com wrote:

 So it's even easier than I said. And bonus lesson for the day: Try
 things in the interactive interpreter before you post. :)

but first: be sure to familiarize yourself with the many built-in
python classes(sic). Re-inventing the wheel is breaking the lazy
programmers' creed. It should only be broken if you wish to understand
how things work under the hood.


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


Re: Tkinter.event.widget: handler gets name instead of widget.

2012-07-09 Thread Rick Johnson
On Jul 9, 12:58 am, Terry Reedy tjre...@udel.edu wrote:
 When posting problem code, you should post a minimal, self-contained
 example that people can try on other systems and versions. Can you
 create the problem with one record, which you could give, and one
 binding? Do you need 4 fields, or would 1 'work'?

I'll firmly back that sentiment. Fredric, if you cannot get the
following simple code events to work properly, then how do you think
you can get events working properly on something more complex?

## START CODE ARTISTRY ##
import Tkinter as tk
from Tkconstants import *

class MyFrame(tk.Frame):
def __init__(self, master, **kw):
tk.Frame.__init__(self, master, **kw)
self.bind('Enter', self.evtMouseEnter)
self.bind('Leave', self.evtMouseLeave)
self.bind('Button-1', self.evtButtonOneClick)

def evtMouseEnter(self, event):
event.widget.config(bg='magenta')

def evtMouseLeave(self, event):
event.widget.config(bg='SystemButtonFace')

def evtButtonOneClick(self, event):
event.widget.config(bg='green')

if __name__ == '__main__':
root = tk.Tk()
for x in range(10):
f = MyFrame(root, height=20, bd=1, relief=SOLID)
f.pack(fill=X, expand=YES, padx=5, pady=5)
root.mainloop()
## END CODE ARTISTRY ##

---
More points to ponder:
---
1. Just because the Tkinter designers decided to use idiotic names for
event sequences does not mean you are required to blindly follow their
bad example (the whole: if johnny jumps off a cliff..., thing comes
to mind)

2. I would strongly recommend you invest more thought into your event
handler identifiers. ALL event handlers should marked as *event
handlers* using a prefix. I like to use the prefix evt. Some people
prefer other prefixes. In any case, just remember to be consistent.
Also, event handler names should reflect WHAT event they are
processing, not some esoteric functionality of the application like
pick_record or info_profile. However if you like, simply have the
event handler CALL an outside func/meth. This type of consistency is
what separates the men from the boys.

3. The Python Style Guide[1] frowns on superfluous white space (be it
horizontal OR vertical!) I would strongly recommend you read and adapt
as much of this style as you possibly can bear. Even if we don't all
get along, it IS *very* important that we structure our code in a
similar style.

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


Re: Python Interview Questions

2012-07-09 Thread Rick Johnson
On Jul 9, 12:40 pm, Tim Chase python.l...@tim.thechases.com wrote:
 The second[or higher]-order
 ignorance of not knowing what pdb is (or, if you need more powerful
 debugging, how to do it) is sign the person hasn't been programming
 in Python much.

So guru knowledge of pdb is prerequisite to being accepted as a
Pythonista? I find that ridiculous since *real* programmers don't use
debuggers anyway.

 [Ed: something appears to have gotten truncated there]  Yeah, it's
 more about a person being sufficiently steeped in python to know
 bits and pieces of the zen, and their ability to recognize/create
 pythonic code.  I've seen enough Java-written-in-Python to know what
 I don't want :-)

I know you are a member of the group who has an aversion to strict OOP
paradigm but is this a justified aversion, or just fear of OOP due to
static evolution? Look, i don't like java's strict approach either,
however, i do not have an aversion to OOP.

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


Re: Tkinter.event.widget: handler gets name instead of widget.

2012-07-10 Thread Rick Johnson
I've tried to condense your code using the very limited info you have
provided. I have removed unnecessarily configuring of widgets and
exaggerated the widget borders to make debugging easier. Read below
for QA.

## START CONDENSED CODE ##
records = range(4)

CNF_SUBFRAME = {
'bd':5, # rowFrame boder width.
'relief':RIDGE,
}

CNF_LABEL = {
'anchor':W,
'width':10,
'bg':'gray',
}

class FooFrame(tk.Frame):
def __init__(self, master, **kw):
tk.Frame.__init__(self, master, **kw)
self.build_records()

def build_records(self):
# Should this method be called by __init__???
# Not sure if records is passed-in or global???
for n in range(len(records)):
record = records[n]
rowFrame = tk.Frame(self, name='-%d-'%n, **CNF_SUBFRAME)
rowFrame.bind ('Enter', self.evtEnter)
rowFrame.bind ('Leave', self.evtLeave)
rowFrame.bind ('ButtonRelease-1',
self.evtButtonOneRelease)
rowFrame.bind ('ButtonRelease-3',
self.evtButtonThreeRelease)
rowFrame.grid (row=n+2, column=1, padx=5, pady=5)
for i in range(4):
lbtext = 'Label_'+str(i)
label = tk.Label(rowFrame, text=lbtext, **CNF_LABEL)
label.grid (row=0, column=i, sticky=NW)

def evtEnter(self, event):
w = event.widget
print 'evtEnter', w.winfo_class()
w.config(bg='magenta')

def evtLeave(self, event):
w = event.widget
print 'evtLeave', w.winfo_class()
w.config(bg='SystemButtonFace')

def evtButtonOneRelease(self, event):
w = event.widget
print 'evtButtonOneRelease', w.winfo_class()
w.config(bg='Green')

def evtButtonThreeRelease(self, event):
w = event.widget
print 'evtButtonThreeRelease', w.winfo_class()
w.config(bg='Blue')

if __name__ == '__main__':
root = tk.Tk()
frame = FooFrame(root, width=100, height=100, bg='red', bd=1)
frame.pack(padx=5, pady=5)
root.mainloop()
## END CONDENSED CODE ##


In the code sample provided, you will see that the label widgets
stacked on each row will block click events on the containing
rowFrames below them. You can get a click event (on the sub frames)
to work by clicking the exaggerated border on the frames. All the
events work properly for me, although this GUI interface seems
unintuitive even with proper borders and colors.

Fredric, I can't help but feel that you are not attacking the problem
correctly. Please explain the following questions in detail so that i
may be able to provide help:

Q1. You have subclassed a Tkinter.Frame and you are building rows of
sub-frames into this toplevel frame; with each row holding
horizontally stacked label widgets. Okay, I can see a need to wrap up
a RowFrame object, but i don't see a need to create a
RowFrameFactory. Can you explain this design decision?

Q2. It seems odd to me that you want to engage the rowFrame widgets
via events but NOT the Label widgets. Can you explain this design
decision?

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


Re: Tkinter.event.widget: handler gets name instead of widget.

2012-07-10 Thread Rick Johnson

Also:

Q3: Why are you explicitly setting the name of your subFrame widgets
instead of allowing Tkinter to assign a unique name?...AND are you
aware of the conflicts that can arise from such changes[1]?

Q4: Are you aware of the built-in function enumerate[2]? I see you
are passing around indexes to iterables AND simultaneously needing the
obj reference itself. I prefer to keep indexing to a minimum.  If
there is no bleeding edge performance issue to worry about (and there
almost *always* never is) why not use enumerate?

[1] 
http://www.pythonware.com/library/tkinter/introduction/x147-more-on-widget-names.htm
[2] http://docs.python.org/release/3.0.1/library/functions.html#enumerate
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Interview Questions

2012-07-10 Thread Rick Johnson
On Jul 10, 4:29 am, Jean-Michel Pichavant jeanmic...@sequans.com
wrote:
 Why would you want to hire someone that knows something pointless as the
 version where feature X has been introduced ? Just tell him that feature
 X has been introducted in version Y, costless 2.5sec training. Don't you
 want to hire someone that knows things you don't and benefit from each
 others abilities, learning from each others, improving the company
 global skill range ?

 JM

Ha! Intelligent people are scary to bosses. They want robots Jean.
Robots that are *just* intelligent enough to reduce their own work
load whist NOT intelligent enough to render them obsolete.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to safely maintain a status file

2012-07-12 Thread Rick Johnson
On Jul 12, 2:39 pm, Christian Heimes li...@cheimes.de wrote:
 Windows's file system layer is not POSIX compatible. For example
 you can't remove or replace a file while it is opened by a process.

Sounds like a reasonable fail-safe to me. Not much unlike a car
ignition that will not allow starting the engine if the transmission
is in any *other* gear besides park or neutral, OR a governor (be
it mechanical or electrical) that will not allow the engine RPMs to
exceed a maximum safe limit, OR even, ABS systems which pulse the
brakes to prevent overzealous operators from loosing road-to-tire
traction when decelerating the vehicle.

You could say: Hey, if someone is dumb enough to shoot themselves in
the foot then let them... however, sometimes fail-safes not only save
the dummy from a life of limps, they also prevent catastrophic
collateral damage to rest of us.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Keeping the Console Open with IDLE

2012-07-15 Thread Rick Johnson
On Sunday, July 15, 2012 10:57:00 AM UTC-5, Chris Angelico wrote:
 On Mon, Jul 16, 2012 at 1:35 AM,  rantingrickjohn...@gmail.com wrote:
  Besides, you can skip most of those steps by Shift+RightClicking
  the file icon and choosing Open Command Window Here.

 That's not standard. Me, I can invoke git bash anywhere I want it, but
 that doesn't mean I'd recommend installing git just so that people can
 get command lines with less steps.

I don't understand Chris? It's obvious that the OP is on a windows box; for 
which no installation is required. 

And, what is so egregious about less steps(sic)? Do you prefer to be 
unproductive? Did you forget the lazy programmers creed? Is your employer 
paying you by the hour? ...all good questions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Rick Johnson
On Sunday, July 15, 2012 11:19:16 AM UTC-5, Ian wrote:
 On Sun, Jul 15, 2012 at 4:56 AM, Steven D'Aprano
 steve+comp.lang.pyt...@pearwood.info wrote:
  (For the record, I can only think of one trap for the unwary: time
  objects are false at *exactly* midnight.)
 
 Ugh, that's irritating.  I can't think of any scenario where I would
 ever want the semantics if timeval (is not midnight):.  This
 reinforces the point that if you only want to test whether you have
 None, you should use is not None rather than relying on __bool__.

I think this issue is not so much a bool test vs type test, but more an 
ambiguous syntax issue. Consider this:

## EXAMPLE A ##
py if money:
... do_something()

The syntax if money implies we are testing/measuring some attribute of 
money, but what exactly about money are we testing/measuring? The problem 
lies in the syntax. To understand this syntax, we must first interpret what 
*IF* means, and we should *NEVER* need to interpret such a well defined word as 
*IF*! This syntax is far too opaque. Consider the alternative:

## EXAMPLE B ##
py if bool(money):
... do_something()

Now we have a hint. Even if we don't understand the inner workings of the 
bool function, we *do* understand that the statement bool(money) *must* 
return True or the block *will not* execute. 

We must NEVER present if in such confusing manner as ExampleA. I believe 
Guido made a grave mistake allowing this syntax to flourish. His intentions 
where noble, to save people a few keystrokes, but all he accomplished was to 
pave a road directly into hell. 

 Explict is better than Implict
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implicit conversion to boolean in if and while statements

2012-07-15 Thread Rick Johnson
On Sunday, July 15, 2012 1:01:58 PM UTC-5, Ian wrote:

 So now instead of having to understand how if handles arbitrary
 values, we have to understand how bool handles arbitrary values.
 How is that an improvement?

Because we are keeping the condition consistent. We are not relying on implicit 
resolution of an object's value based on some dark, esoteric and inconsistent 
rules that defy all normal logic.

 What should if do if presented a value that isn't True or False?
 Raise a TypeError?

YES! Because IT IS the author's responsibility to present a condition that 
evaluates to either True or False. Anything else would be ridiculously 
inconsistent.

 Next thing we know, people get so used to wrapping everything they
 present to if in a bool() call, that they start writing silly
 things like if bool(x == 7) and if bool(isinstance(x, int)).  

We cannot prevent morons from doing stupid things. x==7 IS an explicit 
statement that evaluates to either True or False. Likewise, isinstance(obj, 
type) is a function that evaluates to either True or False. Wrapping either 
example in a bool call is redundant and only obfuscates the meaning. True 
equals True and False equal False. Why do you need to test that truth?

The only time you will be forced to use the bool is when you are NOT using rich 
comparisons or NOT using truth testing functions in a condition. The following 
require NO bool function:

obj == obj - bool
obj != obj - bool
obj  obj - bool
obj  obj - bool
obj = obj - bool
obj = obj - bool
isinstance(obj, type) - bool
callable(obj) - bool
hasattr(obj, name) - bool
issubclass(obj, name) - bool
..along with any function that returns a bool

Whereas: 
if obj - Some esoteric semantics that defies all logic!

 Why?
 Because it's faster and easier to automatically wrap the value in
 bool than it is to put in the effort to verify that the value will
 always be a bool to begin with in order to avoid a useless and
 annoying exception.  

No, because we want our code to be EXPLICIT and consistent! Remember, writing 
obfuscated code is easy, however, interpreting obfuscated code is difficult! A 
good measure of your programming skill is to see how easily your code is read 
by the majority. 

 If it's difficult to explain, it's probably a bad idea. 

if blah is difficult to explain, whereas if bool(blah) is not.   

 At the point that happens, the bool() is
 effectively just part of the if syntax, and we're back to where we
 started.

That's a ridiculous conclusion. See points above^^^

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


Re: How to configure Tkinter Listbox to disable state keeping selected item highlighted

2012-07-18 Thread Rick Johnson
On Tuesday, July 17, 2012 8:55:21 AM UTC-5, Sarbjit singh wrote:
 I am having a problem configuring a listbox widget such that the selection 
 remains highlighted even while it is set (programmatically) to the DISABLED 
 state. Below code shows the problem:
 
 from Tkinter import *
 master = Tk()
 listbox = Listbox(master)
 listbox.pack()
 listbox.insert(END, quot;Text1quot;)
 listbox.insert(END, quot;Text2quot;)
 listbox.insert(END, quot;Text3quot;)
 listbox.selection_set(first=0, last=None)
 listbox.configure(exportselection=False)
 listbox.configure(state=DISABLED)
 
 Now when I change state to NORMAL, selected item is being highlighted. Is 
 there a way I could disable widget (i.e. No response on mouse clicks) but 
 keep the selected object remain highlighted?
 
 Intent: I want to utilise this widget on wizard App that I am creating. I 
 would like this widget to indicate the current page / wizard number which the 
 user selected. Is there any other widget I could use instead of it? (Labels 
 possibly?)



On Tuesday, July 17, 2012 8:55:21 AM UTC-5, Sarbjit singh wrote:
 I am having a problem configuring a listbox widget such that the selection 
 remains highlighted even while it is set (programmatically) to the DISABLED 
 state. Below code shows the problem:
 
 from Tkinter import *
 master = Tk()
 listbox = Listbox(master)
 listbox.pack()
 listbox.insert(END, quot;Text1quot;)
 listbox.insert(END, quot;Text2quot;)
 listbox.insert(END, quot;Text3quot;)
 listbox.selection_set(first=0, last=None)
 listbox.configure(exportselection=False)
 listbox.configure(state=DISABLED)
 
 Now when I change state to NORMAL, selected item is being highlighted. Is 
 there a way I could disable widget (i.e. No response on mouse clicks) but 
 keep the selected object remain highlighted?
 
 Intent: I want to utilise this widget on wizard App that I am creating. I 
 would like this widget to indicate the current page / wizard number which the 
 user selected. Is there any other widget I could use instead of it? (Labels 
 possibly?)

What's wrong with a page number displayed on a label? Why must you insist on 
displaying every page number in a Listbox? That seems like a waste of resources 
to me. You could even say: Showing page I of N.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sudden doubling of nearly all messages

2012-07-21 Thread Rick Johnson
On Saturday, July 21, 2012 5:48:29 AM UTC-5, Dave Angel wrote:
 Has anybody else noticed the sudden double-posting of nearly all
 messages in the python mailing list?
 
 Previously, I#39;ve seen some messages double posted, and it was nearly
 always a newbie, presumably posting via some low-end gateway.  But now
 i#39;m noticing nearly every message appears twice, identical datestamps,
 and usually one message considered a reply to the other.

It's due to the new Google Groups interface. They started forcing everyone to 
use the new buggy version about a week ago EVEN THOUGH the old interface is 
just fine. Another bug: If you look at the text i quoted you will see HTML 
character references. Usually i clean the text before posting but sometimes i 
forget.

Google is starting to SUCK!

You know, i really went out of my way to support Google for many years even 
though i knew they were spying on me. But since they were giving me 
interesting software for free, i did not mind so much. But now they have 
dropped great software and refuse to maintain the software they do have.

Their online docs were a great idea, but have you ever tried to use the docs 
interface for anything serious? S-U-C-K-S! 

Seriously, i can see Google going the way of yahoo soon. Heck, i even use Bing 
as my search engine now. I MUST be a disgruntled customer if i am using the 
search engine of the evil empire!

It was a nice run Google. We had good times and bad times. A few smiles and 
cries. 

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


Re: Sudden doubling of nearly all messages

2012-07-21 Thread Rick Johnson
On Saturday, July 21, 2012 6:16:24 PM UTC-5, Chris Angelico wrote:

 Just to clarify, I'm not advocating the 
[...snip...]

Well. Well. Backpedaling AND brown-nosing in a single post. Nice!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tuples and immutability

2014-03-11 Thread Rick Johnson

On Thursday, February 27, 2014 4:18:01 PM UTC-6, Ian wrote:
 x += y is meant to be equivalent, except possibly in-place and more
 efficient, than x = x + y.  

In an ideal world, the speed of these two codes should be the same, of course 
i'm assuming that most competent language designers would optimise the slower 
version. 

But Rick, Python is an interpreted language and does not benefit from a 
compile stage.

Even if the bytecode can't be optimized on the current run, it CAN be optimized 
by updating the .pyo file for future runs without degrading current (or future) 
runtime performance.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [OFF-TOPIC] How do I find a mentor when no one I work with knows what they are doing?

2014-04-08 Thread Rick Johnson
On Tuesday, April 8, 2014 2:07:27 AM UTC-5, James Brewer wrote:
 I'm sure there will be a substantial amount of arrogance
 perceived from this question, but frankly I don't think
 that I have anything to learn from my co-workers, which
 saddens me because I really like to learn and I know that
 I have a lot of learning to do.
 
 [Blah-blah-blah -- rambling in a feeble attempt to mask my
 question as more than just infantile whining -- blah-blah-
 blah...]
 
 Basically, I want to be a better engineer. Where can I
 find someone willing to point me in the right direction
 and what can I offer in return?

Judging from your childish optimism and bombastic
expectations that the onerous of scholastic achievements lay
solely in the prowess of your teacher, i can only conclude
that you are yet another recent graduate of one of the
fine universities that happily rob naive parents of their
life savings and then infect the professional world with
plagues of self-absorbed little lazy a-holes who think they
offload their workload on everyone else. 

So you want to be taught eh? Maybe you should consider this
little tidbit...

   When the pupil is ready, the master will appear

And now allow me to female dog slap you back in to reality
about your new found masters -- you know, the ones you so
kindly refer to as co-workers...


They are not going to help you! 

They are not going to teach you! 

Heck, they may not even point you in the direction of
the lavatory when you need to tinkle!

No, these people are your mortal enemies. They will smile to
your pimpled face and then stick a knife in your back -- not
much unlike the trolls around here!

Listen kid; working is competition, a competition to the
death, and only the stupidest of stupid person would train
their replacement!

So what is a boy to do? 

I would suggest you learn a little self reliance. Go and
read some tutorials, learn a new language, try to challenge
yourself to build something that is beyond your skill level.
Short of that you'll always be Bubba's female dog.

Good day!

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


Re: threading

2014-04-08 Thread Rick Johnson
A overview of the Py-Venactular used in this thread: 
by Professor Rick


#   Finny Said:#

# Threading is very difficult to get right   #


Hmm, and I wonder how difficult threading would be to get
left? Or perhaps  the proper explanation would be:

Using the Python threading module *correctly* can be
difficult to *contemplate* by mere mortals (and even
most experts, just ask GvR!).
 
Which can be future trimmed to: 

If the implementation is difficult to explain (or use),
it's probably a bad idea. -PythonZen


#Roy Said: #

# Threading makes it incredibly difficult to reason about #
# program execution.  #


Makes what incredibly difficult? Makes *reasoning* very
difficult?


#Roy Said: #

# It's not just that things happen asynchronously, the#
# control flow changes happen at arbitrary times. #


Your first four words are superfluous and could have simply
been replaced with because or since. Below I've joined
both sentences into a complete thought, observe:

Threading renders reasoning of program execution
difficult, because of unpredictable control flow.

Since control flow is unpredictable, use of the Python
threading module is not advised when parallel processing
will suffice.


#   Chris Said:#

# Is it efficient to create processes under Windows?   #


Is what efficient? Creating processes? You just said that!
Now I'm confused? :-(


#   Marko Said:#

# Another way to look at it...[snip]   #


Look at what? There should be no visual learners here. 


#   Marko Said:#

# I don't think it worked out all that well.   #


If you want to poke a stick in someones eye then do it
explicitly, don't be a wuss by using implicit expletives.
Instead you could have post fixed this snarky remark to your
main idea: -- Obviously the attempt was an abysmal
failure!.



#Paul said:#

# I keep hearing about all the perils of threading bugs#
# and it just hasn't happened to me in Python as far as I  #
# know.#


What has not happened to you? threading bugs?


 Summary:

I'm far too lazy to continue on --since the transcribing and
corrections for just this relatively short thread could
take hours--, and my intentions are not to belittle any of
our fine community members, however, sometimes we all need
to be reminded of our own weaknesses. 

I would hope that my fellow members would consider investing
more thought into the structure and coherency of their
posts. A little proof reading can go a long way you know!
But most importantly, i would hope that they might realize
the damage done not only to the coherency of this groups
message from the habitual usage of expletives, but also, to
their own logical expression of ideas.

So, next time you find yourself writing the word it, stop
and ask yourself these questions:

What is it referring to? 

Did i unconsciously use it to beg the question, or
underscore the obvious?

Does the removal of it from this sentence effect the
interpretation of my expression?

You see, there are very few instances where an it is
required, and if you're communication skills 

Re: threading

2014-04-09 Thread Rick Johnson
On Wednesday, April 9, 2014 8:50:59 AM UTC-5, Neil D. Cerutti wrote:
 [...]
 Plus Rufus Xavier Sasparilla disagrees with it.

If you think you're going to argue in such an implicit manner
as to the benefits of pronouns, then you should expect that
an astute logician such as myself will tear you to shreds.


#WARNING:  #

# You cannot wave shiny objects in front of MY eyes and#
# expect me to fold like a lawn-chair! #


And whist i admit your snarky comment is founded on a
*superficial* fact that cannot be denied,(that is: the fact
that pronouns remove superfluous repetition from
communications), most people will be so distracted by the
initial emotional response of laughter, that they will lose
their logical focus and fortitude, and forget to confirm the
validity of your assertion.

Your comment is a fine example of why people like Bill Mahr,
Steve Colbert, and , uh, that other guy??? can pacify
otherwise intelligent people via comedy whist their civil
liberties are robbed from them and justice is ignored. Does
fiddling and Rome ring a bell people?


#Summary:  #

# You comment is cleaver propaganda, but (as we shall all   #
# learn soon) in no way shape or form is your assertion#
# *logical* or *resilient* to interrogations.   #


Now, before i utterly destroy you, we must first *ALL* take
a lesson in linguistics.


#   Define Noun:   #

# a word (other than a pronoun) used to identify any of a  #
# class of people, places, or things   #



#Define Pronoun: #

# In linguistics and grammar, a pronoun is a word or form  #
# that substitutes for a noun or noun phrase.  #


Pronouns are simply shorthands versions of nouns. We use
them to reduce the amount of atomic repetition in our speech
and writing, at that's a good thing! No one wants to inject
superfluous repetition into their prose. This, is the very
argument that my good friend Mr. Cerutti is presenting
with his *esoteric* reference to Rufus Xavier Sasparilla
-- of whom I will refer to from now on as Mr.RXS

Whist i agree with my opponent and MR.RXS on this one tiny
aspect of pronouns, we must dig deeper to understand why
Mr. Cerutti's argument is invalid to the subject matter
for which he is replying. The only way Mr Cerutti's comment
could be valid is if i argued that *ALL* pronouns are
evil, and that is NOT my argument.  MY ARGUMENT IS HIGHLY
SPECIFIC!


#  Inquisitive Joe asks:   #

# But why do you single out it for excommunication  #
# Rick? What is so bad about it?#


My argument is simply that the pronoun it, is a
superfluously implicit use of pronouns! Since it can refer
to either a person, a place or even a thing, it
therefor injects too much ambiguity EVEN when properly[1]
used.

But not only is the ambiguity of the it pronoun an
unfortunate ubiquity, the manner in which the pronoun it
is referenced will many times manifest itself in confusing
manners. Observe the following three sentences which use
it in  illogically ascending orders of incomprehensibility:

1. I ate a burger, and it was good.

The first example is not terribly difficult to grok
since the noun burger is defined before the pronoun
it is declared and then logically bound to burger.

2. It was a good day today.

In the second example we have the it at the very
beginning of the sentence, therefore, i must not only
read and comprehend the remainder of the sentence, but, i
must also remember that i need to find the antecedent of
the initial unbound pronoun it.


3. It irks me that language designers pay no attention
   to consistency.

And the evil incarnation of the IMPLICIT PRONOUN raises
it's ugly head!!!

Again we have the pronoun it declared as the very first
word of the sentence, however, the referent is 

Re: Why Python 3?

2014-04-19 Thread Rick Johnson
On Friday, April 18, 2014 10:28:05 PM UTC-5, Anthony Papillion wrote:
 Hello Everyone,
 So I've been working with Python for a while and I'm starting to take
 on more and more serious projects with it. I've been reading a lot
 about Python 2 vs Python 3 and the community kind of seems split on
 which should be used.
 Some say 'Python 3 is the future, use it for everything now' and other
 say 'Python 3 is the future but you can't do everything in it now so
 use Python 2'.
 What is the general feel of /this/ community? I'm about to start a
 large scale Python project. Should it be done in 2 or 3? What are the
 benefits, aside from the 'it's the future' argument?

Python 3000 is the direct result of a hubris that even
surpasses Hitler's boneheaded attempt to fight the war on two
fronts. Yes, most of us agree that the changes are positive
evolution HOWEVER, are these minor repairs REALLY worth
polarizing a vibrant community and causing Python's
propagation to stagnate?

HELL NO!

Who would want to choose Python for a scripting language for
their project when EVEN the community cannot agree on which
version is best to use? But even *IF* every respected member
was a total high-knee smooching tool of GvR parroting off
that Python 3000 is the best!, we cannot ignore the
functionality concerns that will result from choosing
between 2x or 3x.

NOBODY IS ACTIVELY CHOOSING PYTHON ANYMORE FOLKS!

Python is destined to destroy itself internally JUST like
the American society is currently destroying itself, and
what a travesty, since Python was the shining light of what
a program should be.

THE REVOLUTION WILL NOT BE TELEVISED!

Python is set to become extinct because GvR bought his time
machine AFTER infecting the code base with a print
statement -- thanks Guido, thanks for everything! Maybe next
time you should consider buying bean stalk beans instead!


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


Return of an old friend

2011-11-24 Thread Rick Johnson
Hello Fellow Pythonistas,

I am very glad to be back after an unfortunate incident caused my
Google account to be deleted. Unfortunately for those of you that have
been following along and supporting my crusade to bring fairness and
humility to the python community, my old posts under rantingrick
have all been deleted from Google Groups. However, you can always
search the python-list archives if you need a jog down memory lane.

Actually this accidental deletion may have been a good thing as i've
had some extra time to muse on the innards of Python4000.

In any event, this announcement is intended to be a new call to arms
for my brothers and sisters who fight the good fight, and for those of
you who despise me , well, this might be a good time to add my new
moniker to your kill files.

Thanks, and happy Thanksgiving everyone!
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   8   9   10   >