Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Why should i use python if i can use java

5 views
Skip to first unread message

mik

unread,
Jun 6, 2001, 2:52:34 PM6/6/01
to
i' m a python newbie but I've this prob. i have seen Jython ..

what has python dat java does not?????????


Martijn Faassen

unread,
Jun 6, 2001, 3:55:08 PM6/6/01
to
mik <karme...@hotmail.com> wrote:
> i' m a python newbie but I've this prob. i have seen Jython ..

I'm not sure how that is a problem. Is it a problem?

> what has python dat java does not?????????

Python has everything Java has got (through Jython) and then some!
Of course Java has a lot of what Python has got (through Jython)
as well.

Python is a more pleasant and easy to use language than Java, according
to many of its users. It's easier for beginners and doesn't stand in
the way of more experienced programmers either. People claim they
can develop software more quickly using Python.

Python takes another approach than Java; Java is a "We are the World"
language; in Java land, virtually everything is supposed to be
in Java or at least have a very thick layer of Java covering it. This
has advantages (compatibility and portability can sometimes be easier
to ensure), but also disadvantages (integration with other tools and
systems is more difficult). Python is a far more open language
and integrates well with a lot of external tools and libraries.

Java code is reputed to execute faster than Python code; though
this depends on the algorithm a lot, and many claim it's easier to
be smarter in Python about it (and thus faster) than in Java. Python
tends to consume less memory than Java does.

If Java or Python or some other language is best for you depends on
what you'd like to do, so you'll have to figure that out first.

Regards,

Martijn

D-Man

unread,
Jun 6, 2001, 4:13:27 PM6/6/01
to pytho...@python.org
On Wed, Jun 06, 2001 at 08:52:34PM +0200, mik wrote:
| i' m a python newbie but I've this prob. i have seen Jython ..
|
| what has python dat java does not?????????

Modules. Function objects. _Completely_ OO (int, boolean, modules,
classes, and functions are all objects, not just class instances).
Easier syntax. High level of design in the language and runtime
libraries. No casting when using containers. Edit-run as opposed to
edit-compile-run cycle.

In short, Python has a _lot_ that Java doesn't have. Jython is an
implementation of Python written in Java so that it runs in a JVM and
provides nice integration between Python and Java similar to what
CPython does for C and Python.

-D


Alex Martelli

unread,
Jun 6, 2001, 5:56:52 PM6/6/01
to
"D-Man" <dsh...@rit.edu> wrote in message
news:mailman.991858449...@python.org...

> On Wed, Jun 06, 2001 at 08:52:34PM +0200, mik wrote:
> | i' m a python newbie but I've this prob. i have seen Jython ..
> |
> | what has python dat java does not?????????
>
> Modules. Function objects. _Completely_ OO (int, boolean, modules,
> classes, and functions are all objects, not just class instances).
> Easier syntax. High level of design in the language and runtime
> libraries. No casting when using containers. Edit-run as opposed to
> edit-compile-run cycle.

And higher productivity. I thought I had posted a huge treatise
on that just a few hours ago to a heavily crossposted thread
with a funny subject about 3D, but it doesn't seem to have
shown up, I'll have to look into that... it mentioned Prechelt's
empirical study, quoted Eckel extensively, etc, etc.


> In short, Python has a _lot_ that Java doesn't have. Jython is an
> implementation of Python written in Java so that it runs in a JVM and
> provides nice integration between Python and Java similar to what
> CPython does for C and Python.

Far better! Jython's total integration with Java's libraries is
astonishing. You don't need to 'wrap' anything, like you do
in CPython with a typical C library... just USE it -- any Java
library is right there, ready for your Jython use. I can't get
over the detail of how SMOOTHLY it works...!-)

Caveat: it takes an *up-to-date* JVM, so, just like anything
else added to Java after 1.0, it's *NO* good for applets that
must run on any comer's browsers (most browser out there
use VERY old and/or quirky JVMs and you can't expect a
site's visitors to download many megabytes of plugin from
javasoft's site just to be able to enjoy your site:-).


Alex

Geoffrey Gerrietts

unread,
Jun 6, 2001, 6:31:59 PM6/6/01
to pytho...@python.org
mik <karme...@HOTMAIL.COM> asks:

> i' m a python newbie but I've this prob. i have seen Jython ..
>
> what has python dat java does not?????????

As someone who just recently spent a lot of time on this group explaining
Java's benefits, I think my karma may demand something of an about face. I
can't tell you what you'll like best about Python, or what you'll use most,
but I can tell you how things have worked for me.

I think it can be summed up in a sentence: Python is a lot more flexible
than Java. That doesn't mean that you can do some things in Python that you
can't in Java; it just means that some things are much easier to do in
Python than in Java. I might go so far as to say most things.

Reflection in Java is a pain in my ass. It's inconvenient and it's pretty
difficult to get at the actual methods or properties to call them. Python
makes that very simple, to the point of trivial. Python makes it very easy
to grab hold of what you want when you want it. It's a lot easier for me to
write components that can accomodate any object at all without relying on
whether standard interfaces have been implemented. It's also very easy to
manipulate functions or methods, copy them between objects, or otherwise
manipulate the results of my introspection.

Unit-testing under Python is a lot easier, or has proven so for me. Because
you have almost total control over the objects you import and use, you can
stick in "stubs" for standard library components, so that your "stub"
returns standardized values. You can also do it for user-contributed
components.

Prototyping and experimenting is easier under Python, too. I slap together a
few lines of code into a file, then python -i <filename> -- the Python
interpreter runs my lines, then gives me a command prompt, so I can
experiment with the data, try various combinations of function calls, or
otherwise validate my work.

In Python, I know how to write classes whose instances are other classes. In
Python, I know how to write a routine that generates a string of python
code, then executes the contents of the string. These are highly dynamic
features that I don't know how to exploit in Java, if it's even practical to
do so. Note that you /can/ do it in Java, but it may take you ten or twenty
or a thousand lines of Java to do what one or two or five lines of Python do
quite easily.

These are all features I can say that I've used in Python -- used the hell
out of some of them. They lack in Java, or are more difficult to access.

---
Geoff Gerrietts <ge...@homegain.com>
Software Engineer, HomeGain.com
510-655-0800 x4320

Erik Max Francis

unread,
Jun 6, 2001, 10:41:07 PM6/6/01
to
mik wrote:

> i' m a python newbie but I've this prob. i have seen Jython ..
>
> what has python dat java does not?????????

No one's forcing you to use Python. If you prefer Java, so be it.

--
Erik Max Francis / m...@alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/ \ Life is something to do when you can't get to sleep.
\__/ Fran Lebowitz
Official Omega page / http://www.alcyone.com/max/projects/omega/
The official distribution page for the popular Roguelike, Omega.

Chris Goringe

unread,
Jun 7, 2001, 12:02:38 AM6/7/01
to
I'm just completing my first significatn project in python (previously
worked in Java). Productivity gain in python has been significant.
However, python doesn't

strong typing (love it or hate it...)
interfaces (ditto)
an elegant way of implementing singletons (or does it? anyone?)
a comparable development and debugging environment to JBuilder

but most of all, it doesn't have

J2EE
J2ME

So it still lags Java for seriously scalable enterprise solutions and
for portable device deployment.

Chris

Glyph Lefkowitz

unread,
Jun 7, 2001, 1:43:57 AM6/7/01
to pytho...@python.org

On 6 Jun 2001, Chris Goringe wrote:

!snip!

> python doesn't [have ...]


> strong typing (love it or hate it...)

Hate it :)

> interfaces (ditto)

Well, python *does* have interfaces, at a much deeper level than Java; you
could think of *everything* in python as going through an interface. What
it doesn't have is interface implementation enforcement; which is nice,
because that means that as long as your classes implement the bits of the
interface you need, minor changes to the code of a library you're using
won't break everything instantly. I also chuckle to think that the
compiler can tell if I've properly implemented actionPerformed, or if I'm
just stubbing it out by copying the declaration from the interface file.

> an elegant way of implementing singletons (or does it? anyone?)

Aah, the singleton. Global variables for the new millennium. First of
all, the singleton "pattern" is usually a bad idea. If you have a class
that can "only be instantiated once", then you're dealing with per-process
state, and representing it as a class instance can be misleading. If it's
*not* per-process, then you just have a one-to-many relationship of
objects, not a true "singleton"; attempting to limit this artificially is
a mistake and results in reduced flexibility as well as increased
complexity.

Thankfully, Python provides a much better mechanism for doing so!
"Modules" are actually singletons wearing funny shoes. Any "singleton"
state can be specified as a variable in a module. (Which is usually
declared with the 'global' keyword. Coincidence?)

So, I'd say that this is a flaw with Java not supporting modules, rather
than Python not supporting java's ill-defined crutch which it uses to
cover for its lack of support for first-class namespaces and modules,
fancy terminology notwithstanding.

Since we're on the topic; other design patterns that lurk around
unobtrusively in Python include the "for" keyword, which is really the
"Observer" pattern, the notion of classes as callable, which is the
"Factory" pattern universally applied, and the Strategy pattern
masquerading as first-class functions. Modules moonlight as the "Facade"
pattern when they're not playing Singleton. Did guido use the time
machine to get a copy of the GoFBook before he started working on the
first version of Python, or are Patterns just a transparent attempt to
cover for chronically inexpressive languages like C++ and Java which can't
generally implement these mind-numbingly simple constructs in code?
Inquiring minds want to know.

> a comparable development and debugging environment to JBuilder

Have you used any of the commercial Python IDEs? PythonWorks or WING IDE?

> but most of all, it doesn't have
>
> J2EE
> J2ME

Actually it does! With Jython, you can access any Java API from Python.
Neat, huh?

> So it still lags Java for seriously scalable enterprise solutions

(Assuming we're talking about [C]Python, since Jython is functionally
equivalent to Java in terms of available technology --) It depends how you
want to scale. I disagree, but this gets into a very lengthy and
essentially unwinnable argument about development practices. However,
some "enterprises", such as Google, seem to have implmented really massive
things with Python and I don't think they've noticed that it doesn't work.
Also, see Zope.

> and for portable device deployment.

Python is currently very difficult to pare down to embedded devices
currently, bit I imagine that it'll be different in 2 years. However,
once you're up to a certain critical mass, Python's performance tends to
be more deterministic than Java's, so medium-sized "information
appliances" can benefit from Python.


in-languages-that-don't-suck-we-call-"design-patterns"-by-their-real-names-ly
y'rs,

______ __ __ _____ _ _
| ____ | \_/ |_____] |_____|
|_____| |_____ | | | |
@ t w i s t e d m a t r i x . c o m
http://twistedmatrix.com/users/glyph

Alex Martelli

unread,
Jun 7, 2001, 4:39:42 AM6/7/01
to
"Alex Martelli" <ale...@yahoo.com> wrote in message
news:9fm97...@enews1.newsguy.com...
...

> And higher productivity. I thought I had posted a huge treatise
> on that just a few hours ago to a heavily crossposted thread
> with a funny subject about 3D, but it doesn't seem to have
> shown up, I'll have to look into that... it mentioned Prechelt's
> empirical study, quoted Eckel extensively, etc, etc.
...
Seems to have disappeared, so, here we go again:


> I admit, often Java is slower than C++, but whether your keystroke
> will get displayed after 10ms or 20ms within a text editor doesn't
> play any role, does it?

It doesn't -- which is why one should use highly-productive
Python (or Jython, if you prefer to have a JVM underneath --
it's the same language either way, in one case you use fine
tuned C-coded libraries, in the other any Java library) for
as much as possible of one's applications (typically around
90%, depending on the kind of things you do -- the other
10% [may vary from 0% to 30% on different classes of apps]
is too speed-critical).


> Cross-platform development and the ability to have a running BETA
> program before C++ programmers even have a concept.

Have a look at (a preview of) Bruce Eckel's forthcoming "Thinking
in Patterns" chapter 9, e.g. at
http://www.cis.ohio-state.edu/~cguo/books/ThinkingInPatterns/html/Chapter09.
html
(there may be better-updated versions). Eckel, of course, is
quite a Java enthusiast, best-selling author of "Thinking in
Java", etc, etc. He writes as the chapter's conclusion:
"""
To me, Python and Java present a very potent combination for
program development because of Java’s architecture and tool set,
and Python’s extremely rapid development (generally considered to
be 5-10 times faster than C++ or Java). Python is usually slower,
however, but even if you end up re-coding parts of your program
for speed, the initial fast development will allow you to more
quickly flesh out the system and uncover and solve the critical
sections. And often, the execution speed of Python is not a problem
– in those cases it’s an even bigger win. A number of commercial
products already use Java and JPython, and because of the terrific
productivity leverage I expect to see this happen more in the future.
"""

I fully concur with his evaluation of a 5-10 times productivity
advantage for Python vs C++ (speaking as a C++ expert here) --
in my (more limited) experience with Java the productivity
advantage wrt C++ was about 20% to 30%, so (if this holds on
a wider field of applications) the Python/Java ratio would
be more like "just" 3 to 8 times the programmer's productivity.

The ratio in terms of *numbers of line of code* (a VERY rough
measure, but known to hold surprisingly well as a measure of
"language level" -- lines of code per Function Point -- and
thus, indirectly, productivity in both development _and_
maintenance phases) tends to be on the order of 5/6 times
as many lines of Java (or C++, assuming one IS using rich
libraries, such as those at www.boost.org, wxWindows, &c)
per line of Python -- and note that Python does NOT come
from a "one-liner culture" a la APL or Perl:-). Very roughly,
this would seem to confirm the order of magnitude of
productivity advantage (assuming speed concerns do not
interfere and need re-coding of some parts, which would
push development times closer together).

Prechelt's empirical study (there should be more of those
in this field...!-) gives more nuanced results. He
grouped several language into two groups, and he only
was able to observe smaller differences.
http://www.ubka.uni-karlsruhe.de/cgi-bin/psview?document=ira/2000/5
is one URL where you can find the full article in several
formats. Summarizing conclusions:

He noticed a programmer-productivity advantage of about
a factor of 2 for "scripting" (Python, Perl, Rexx, Tcl)
vs "compiled" (C, C++, Java). Typical memory consumption
for script about twice that of c/c++, for Java another
factor of two higher than script. Initialization-phase
performance, C/C++ about 3/4 times faster runtime than
Java, about 5/10 compared to scripts. Main-phase
performance, C/C++ about 2 times faster than Java,
Scripting also faster than Java. Python and Perl
always faster than Rexx and Tcl. Variation in all
performance measures is larger between programmers
in the same language, than between groups of programs
in different languages (man still counts for more
than machine:-).

One little detail -- 80 programs in all were examined,
all solving the same problem -- 5 in Rexx, 8 in C, ...
up to 26 in Java (Java most popular). Totally unusable
programs were as high as 3 in 8 submitted in C (so all
the rest of the study including the above conclusion
only studies the other 5:-), 3 of 14 in C++, 2 of 26
in Java. Python (0 unusable programs out of 13 that
were submitted) was the ONLY language in which *NO*
unusable programs were submitted. Statistical fluke,
no doubt, but...:-).

For performance, see in particular:
http://www.ubka.uni-karlsruhe.de/cgi-bin/psview?document=ira/2000/5&format=1
&page=14
You'll see the Rexx horrid-performance is dragging
down the "Script" group all by itself. Examining
language by language, one can get an idea...:-).


Alex (Brainbench MVP for C++, but Python enthusiast:-)

Alex Martelli

unread,
Jun 7, 2001, 5:19:50 AM6/7/01
to
"Glyph Lefkowitz" <gl...@twistedmatrix.com> wrote in message
news:mailman.991892413...@python.org...

>
> On 6 Jun 2001, Chris Goringe wrote:
>
> !snip!
>
> > python doesn't [have ...]
> > strong typing (love it or hate it...)
>
> Hate it :)

What _I_ hate is the confusion between weak vs strong typing
AND static vs dynamic typechecks, though it's a classic one:-).
Weak typing, properly, is what (e.g.) Perl has, where you can
use any scalar wherever, and it will try to guess what you
mean, freely treating strings as numbers, viceversa, etc.
What Python has (like, say, Scheme) I'd call strong typing
that is dynamically enforced. E.g.:

D:\py21>python
Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
Alternative ReadLine 1.4 -- Copyright 2001, Chris Gonnerman
>>> "ciao"[1.0]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: sequence index must be integer
>>>

That's *WEAK* typing?! I call it pretty strong indeed --
and love it! (Java works similarly here -- it's an
error to use a non-integer as array index -- although
C and C++ happily accept the float and truncate it...).
It's *DYNAMICALLY* checked and enforced, not statically.
I think it's more precise and useful to draw the
distinction as static vs dynamic than as strong
vs weak, no matter which way one wants to argue
for or against it.


> > interfaces (ditto)
>
> Well, python *does* have interfaces, at a much deeper level than Java; you

...but no way to specify them precisely and explicitly (not
that Java excels here, since it lacks preconditions and
postconditions on interfaces, sigh). Anyway, PEPs 245 and
246 would help a lot with this, I think!


> > an elegant way of implementing singletons (or does it? anyone?)
>
> Aah, the singleton. Global variables for the new millennium. First of
> all, the singleton "pattern" is usually a bad idea. If you have a class

*AMEN, HALLELUJAH*! This makes two of us sharing this dislike
for the Singleton Design Pattern, so I'm not a Singleton any
more -- see, that's one typical issue with Singleton DP, what
starts out as a singleton often becomes not one:-).

> that can "only be instantiated once", then you're dealing with per-process
> state, and representing it as a class instance can be misleading. If it's

Yes. You may want to use instances because of flexible
arrangements you can make regarding all sorts of operations
(calls, attribute accesses/bindings, etc etc) through special
methods (in Python, at least:-). But separating the two
issues is simpler and thus preferable: have the instances
(if instances are needed) be freely created, shared, deleted,
etc -- it suffices that the instances *DO NOT HAVE SPECIFIC
PER-INSTANCE STATE* but 'delegate' all of their state to
the "object appearing but once" (a "singleton" by some way
to mean this word, but not a singleton Design Pattern:-).


> Thankfully, Python provides a much better mechanism for doing so!
> "Modules" are actually singletons wearing funny shoes. Any "singleton"
> state can be specified as a variable in a module. (Which is usually
> declared with the 'global' keyword. Coincidence?)

Today you can also have an instance masquerading as a module,
as it happens -- delicate, but it does mean you can control
attribute setting and getting on a "module"!-) Witness:

D:\py21>python
Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
Alternative ReadLine 1.4 -- Copyright 2001, Chris Gonnerman
>>> class AllAttrStrings:
... def __setattr__(self, name, value):
... if type(value)!=type(''):
... raise TypeError,"Attributes must be strings"
... self.__dict__[name]=value
...
>>> import sys
>>> sys.modules['AAS']=AllAttrStrings()
>>> import AAS
>>> AAS.foo='bar'
>>> AAS.foo
'bar'
>>> AAS.peep=23
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 4, in __setattr__
TypeError: Attributes must be strings
>>>

The "import AAS" references the instance-object that
is masquerading as a module, once the appropriate entry
in sys.modules is properly initialized, no matter what
other module IS importing AAS. Now, used with care and
good taste of course, ISN'T this cool...?!-)


> > but most of all, it doesn't have
> >
> > J2EE
> > J2ME
>
> Actually it does! With Jython, you can access any Java API from Python.
> Neat, huh?

Absolutely! But does any commercial IDE, as you earlier
referenced, support Jython yet? I don't know of any.


Alex

Andy Freeman

unread,
Jun 7, 2001, 12:50:30 PM6/7/01
to
> I'm just completing my first significatn project in python (previously
> worked in Java). Productivity gain in python has been significant.
> However, python doesn't
>
> strong typing (love it or hate it...)
> interfaces (ditto)
> an elegant way of implementing singletons (or does it? anyone?)
> a comparable development and debugging environment to JBuilder

Umm, I'm confused. Are you saying that python isn't good/better
because it lacks those things or that Python would be even better
if it did? The former is contradicted by your experience while
the latter is open to debate.

Other people have commented/will comment on interfaces, singletons,
and good development/debugging environments, so after an aside on
typing (dynamic typing is required for truely useful polymorphic
programming, so that typing "a+b" once is reusable), I'll take a
contrary view wrt development and debugging.

I've found that "good" (beyond print/grep) debugging/program development
environments actually decrease "functionality provided" productivity.
(They do seem to increase "lines of code generated" and "% of time
spent typing" productivity.) The reason seems to be that "good"
environments let me/other people write code that is surprising, that
can only be understood through the use of such tools. (Of course,
you can always add user-side hacks when the behavior doesn't match
the documentation, pushing a bigger hairball to the next person.) Without
those tools, me/they have to walk away from the keyboard and figure
out what the problem actually is. It turns out that "figure out" is
more productive than "tools required".

It took me a while to figure this out.



> J2EE
> J2ME
>
> So it still lags Java for seriously scalable enterprise solutions and
> for portable device deployment.

Umm, don't confuse "java environments for accomplishing <goal>" with
"required environments for accomplishing <goal>". Both of those
things are done perfectly well without Java. (Of course, certain
decisions might preclude the use of certain technologies.)

We're about to see whether "write once, run anywhere" will survive
"write anything, works together".

-andy

ps - For those of you with a historical bent, remember when Common Lisp was
way too big? Guess what's smaller - Java (as deployed) or CL (including
a compiler, bignums, ...).

D-Man

unread,
Jun 7, 2001, 12:22:33 PM6/7/01
to pytho...@python.org
On Thu, Jun 07, 2001 at 11:19:50AM +0200, Alex Martelli wrote:

Ditto to all the Dynamic, but still strong, typing and the Design
Patterns discussion explaning why Java is _still_ a very low level
language even though it is bytecode-compiled and interpreted.



| > > but most of all, it doesn't have
| > >
| > > J2EE
| > > J2ME
| >
| > Actually it does! With Jython, you can access any Java API from Python.
| > Neat, huh?
|
| Absolutely! But does any commercial IDE, as you earlier
| referenced, support Jython yet? I don't know of any.

Not commercial, but (g)vim supports this! <smirking grin> Version
6.0 is nearly finished and has some really cool new features including
"folding" (the ability to collapse a block of text into a single line
on the display).

-D


Don Dwiggins

unread,
Jun 7, 2001, 12:49:36 PM6/7/01
to Alex Martelli, pytho...@python.org
Alex Martelli quotes Glyph Lefkowitz:

>> > an elegant way of implementing singletons (or does it? anyone?)
>>
>> Aah, the singleton. Global variables for the new millennium. First of
>> all, the singleton "pattern" is usually a bad idea. If you have a class

> *AMEN, HALLELUJAH*! This makes two of us sharing this dislike
> for the Singleton Design Pattern, so I'm not a Singleton any
> more -- see, that's one typical issue with Singleton DP, what
> starts out as a singleton often becomes not one:-).

According to the GOF "Applicability" section on Singleton:
Use the Singleton pattern when
- there must be exactly one instance of a class, and it must be
accessible to clients from a well-known access point.
- when the sole instance should be extensible by subclassing, and
clients should be able to use an extended instance without modifying
their code.

If you take the whole description of the Singleton pattern seriously, to say
that you "hate" the pattern would seem to mean that you don't believe that
programs should ever need something that satisfies these criteria. Is that
true for both of you? Whether it is or not, I'd like to hear a bit more
explanation for the strong emotional reaction to the pattern.

(I suppose I should mention that I've only used the pattern once, in a C++
program, to hold a transformed version of the parameter list to the program.
It seemed like a reasonable usage -- although I didn't need subclassing --
since the various parameters were accessed in a variety of places in the
code, and needed some interpretation, validation, and processing before
use. In Smalltalk I probably would have used a class that was never
instantiated -- a "system-supplied" singleton.)

--
Don Dwiggins "Solvitur Ambulando"
Advanced MP Technology
dw...@advancedmp.net


James_...@i2.com

unread,
Jun 7, 2001, 1:31:39 PM6/7/01
to pytho...@python.org

Geoff Gerrietts <ge...@homegain.com> wrote:
<snip>

>In Python, I know how to write classes whose instances are other classes.

Do you mean "whose instances are *themselves* classes"? And if so, How do
you do this?
(Can you do this in *Python* -- without doing a C extension?)

Thanks,

Jim

<snip>
>Geoff Gerrietts <ge...@homegain.com>

James_...@i2.com

unread,
Jun 7, 2001, 1:50:34 PM6/7/01
to pytho...@python.org

Alex Martelli wrote:
<snip>

>Far better! Jython's total integration with Java's libraries is
>astonishing. You don't need to 'wrap' anything, like you do
>in CPython with a typical C library... just USE it -- any Java
>library is right there, ready for your Jython use. I can't get
>over the detail of how SMOOTHLY it works...!-)

I agree completely. Using JPython/Jython we've developed (and released :-)
) a family of very sophisticated B2B applications -- comprising several
hundred-thousands of lines of code -- that are in deployment at a number of
very large companies with hundreds (ramping up to thousands) of end-users
each. The UIs had to be built using the Java/Swing libraries; and Jython
made it a breeze. Building Swing UI's using Jython is *much* better than
doing it in Java!

<snip>
>Alex

Jim


D-Man

unread,
Jun 7, 2001, 1:26:36 PM6/7/01
to pytho...@python.org
On Thu, Jun 07, 2001 at 09:49:36AM -0700, Don Dwiggins wrote:
| Alex Martelli quotes Glyph Lefkowitz:
| >> > an elegant way of implementing singletons (or does it? anyone?)
| >>
| >> Aah, the singleton. Global variables for the new millennium. First of
| >> all, the singleton "pattern" is usually a bad idea. If you have a class
|
| > *AMEN, HALLELUJAH*! This makes two of us sharing this dislike
| > for the Singleton Design Pattern, so I'm not a Singleton any
| > more -- see, that's one typical issue with Singleton DP, what
| > starts out as a singleton often becomes not one:-).
|
| According to the GOF "Applicability" section on Singleton:
| Use the Singleton pattern when
| - there must be exactly one instance of a class, and it must be
| accessible to clients from a well-known access point.
| - when the sole instance should be extensible by subclassing, and
| clients should be able to use an extended instance without modifying
| their code.
|
| If you take the whole description of the Singleton pattern seriously, to say
| that you "hate" the pattern would seem to mean that you don't believe that
| programs should ever need something that satisfies these criteria. Is that
| true for both of you? Whether it is or not, I'd like to hear a bit more
| explanation for the strong emotional reaction to the pattern.

Alex Martelli discussed his views with me a couple months ago. He
explained that flyweight proxies can serve the same need as a
singleton, but without the subtle problems the Single DP can present.
The flyweight proxies don't hold any state of their own, but rather
delegate everything to the single instance of a private class. The
proxies can be copied around, instantiated at will, etc. They are
"normal" objects. This issue is especially important in C++ where the
compiler can automatically create and call a copy constructor for your
object.

This is a very brief summary of what Alex showed me. I'm sure he will
see your question and give you the long, detailed, explanation he is
so skilled at :-).

-D


James_...@i2.com

unread,
Jun 7, 2001, 2:31:12 PM6/7/01
to pytho...@python.org

Alex Martelli wrote:
<snip>

>Absolutely! But does any commercial IDE, as you earlier
>referenced, support Jython yet? I don't know of any.
>
>Alex

I use a hybrid approach. For example, I run JBuilder and use its design
layout tool (using Swing components) to do some GUI design: start with a
JPanel, add a JSplitPane, drop in a JTree, and a JTable, some JButtons,
etc. Use the property editor to set property values. Give each component
a name. (I frequently use GridBagLayouts to position things nicely, btw.)
Then I compile and run it in JBuilder until it looks ok. Now I start
writing in Jython. I import the class created by JBuilder, make an
instance of it -- a JPanel subclass typically -- and add in handlers for
the buttons, trees, lists, tables, etc. Each of these (JComponents) I
reference using the name that I assigned to the component when using
JBuilder (I have a little utility method that can search a JComponent and
all of its child components to find a component with a given name). From
there on out, its all Jython. Works like a charm! (Actually, pdb doesn't
work very well when using Swing -- which can be a major pain sometimes.:
-( )

Jim

Alex Martelli

unread,
Jun 7, 2001, 3:56:36 PM6/7/01
to Don Dwiggins, pytho...@python.org
"Don Dwiggins" <dw...@advancedmp.net> writes:
...

> Alex Martelli quotes Glyph Lefkowitz:
> >> > an elegant way of implementing singletons (or does it? anyone?)
> >>
> >> Aah, the singleton. Global variables for the new millennium. First of
> >> all, the singleton "pattern" is usually a bad idea. If you have a
class
>
> > *AMEN, HALLELUJAH*! This makes two of us sharing this dislike
> > for the Singleton Design Pattern, so I'm not a Singleton any
> > more -- see, that's one typical issue with Singleton DP, what
> > starts out as a singleton often becomes not one:-).
>
> According to the GOF "Applicability" section on Singleton:
> Use the Singleton pattern when
> - there must be exactly one instance of a class, and it must be
> accessible to clients from a well-known access point.
> - when the sole instance should be extensible by subclassing, and
> clients should be able to use an extended instance without modifying
> their code.
>
> If you take the whole description of the Singleton pattern seriously, to
say
> that you "hate" the pattern would seem to mean that you don't believe that
> programs should ever need something that satisfies these criteria. Is
that

First of all, I said not 'hate' but 'dislike', and Glyph said "it's usually
a bad idea". But the crucial thing is: I opine the SDP does *NOT*
tend to optimally resolve the forces thus identified!

> true for both of you? Whether it is or not, I'd like to hear a bit more
> explanation for the strong emotional reaction to the pattern.

I've posted very extensively about it, and how I prefer 'lightweight
proxies' instead -- instances that have no state (but rather delegate
all state, and possibly all behavior, to a singly-instanced object not
exposed directly to client code) but are freely instantiable at need -- and
specifically what different advantages this brings in different contexts,
such as Python, COM, and so on. Of all the issues, the key one is that
LWP is more change-proof than SDP in my experience -- "there must
be only one" is, out of all design constraints, one of those that most
tend to change in an iteration. Refactoring LWP's is trivial, refactoring
SDP typically isn't.

But take the subclassing. Why should different client parts need the
same subclassing? They may want to use different mixins, decorators,
and so on. How do they do that on SDP? They don't. How do they
do that on LWP? Trivial. Of course, the in-one-single-instance obj
(not exposed to normal client code) may be subclassed at will (and
variously played with in Python) if something is needed that all
clients will 'see' at once -- as LWP's delegate state & behavior.


Alex



_________________________________________________________
Do You Yahoo!?
Get your free @yahoo.com address at http://mail.yahoo.com

Alex Martelli

unread,
Jun 7, 2001, 4:02:58 PM6/7/01
to
"D-Man" <dsh...@rit.edu> wrote in message
news:mailman.991931005...@python.org...
...

> On Thu, Jun 07, 2001 at 11:19:50AM +0200, Alex Martelli wrote:
>
> Ditto to all the Dynamic, but still strong, typing and the Design
> Patterns discussion explaning why Java is _still_ a very low level
> language even though it is bytecode-compiled and interpreted.

Well, not VERY low...!-). Just lower than Python...


> | > Actually it does! With Jython, you can access any Java API from
Python.
> | > Neat, huh?
> |
> | Absolutely! But does any commercial IDE, as you earlier
> | referenced, support Jython yet? I don't know of any.
>
> Not commercial, but (g)vim supports this! <smirking grin> Version

GVIM rules (5.8's what I'm using now), but I doubt even 6.0 provides
me with a Jython debugger &c...?-)

> 6.0 is nearly finished and has some really cool new features including
> "folding" (the ability to collapse a block of text into a single line
> on the display).

Cool indeed (I'm sure the EMACSers are laughing at us of course:-).


Alex

Don Dwiggins

unread,
Jun 7, 2001, 6:36:19 PM6/7/01
to Alex Martelli, pytho...@python.org
Alex Martelli writes:
> I've posted very extensively about it, and how I prefer 'lightweight
> proxies' instead -- instances that have no state (but rather delegate
> all state, and possibly all behavior, to a singly-instanced object not
> exposed directly to client code) but are freely instantiable at need -- and
> specifically what different advantages this brings in different contexts,
> such as Python, COM, and so on. Of all the issues, the key one is that
> LWP is more change-proof than SDP in my experience -- "there must
> be only one" is, out of all design constraints, one of those that most
> tend to change in an iteration. Refactoring LWP's is trivial, refactoring
> SDP typically isn't.

Sorry, I guess I missed those posts. From the above, it sounds like you
still start with an SDP-style singleton for the proxies to "point at", then
add the LWP class for users to instantiate; this is essentially a Bridge,
which fits your description of the advantages -- you allow the "state
package" to be changed while not affecting the clients and, as you also
describe, you can evolve the LWP separately (e.g., subclassing). It looks
to me as though, rather than replacing one pattern with another, you've
created a nice composition of two patterns. Of course, your LWPs, being
Featherweights, could be used in other ways as well.

D-Man

unread,
Jun 7, 2001, 6:21:40 PM6/7/01
to pytho...@python.org
On Thu, Jun 07, 2001 at 10:02:58PM +0200, Alex Martelli wrote:
| "D-Man" <dsh...@rit.edu> wrote in message
| news:mailman.991931005...@python.org...
| ...
| > On Thu, Jun 07, 2001 at 11:19:50AM +0200, Alex Martelli wrote:
| >
| > Ditto to all the Dynamic, but still strong, typing and the Design
| > Patterns discussion explaning why Java is _still_ a very low level
| > language even though it is bytecode-compiled and interpreted.
|
| Well, not VERY low...!-). Just lower than Python...

Sometimes (far too often, especially when writing unit tests) Java
feels very low level.

| > | > Actually it does! With Jython, you can access any Java API from
| Python.
| > | > Neat, huh?
| > |
| > | Absolutely! But does any commercial IDE, as you earlier
| > | referenced, support Jython yet? I don't know of any.
| >
| > Not commercial, but (g)vim supports this! <smirking grin> Version
|
| GVIM rules (5.8's what I'm using now), but I doubt even 6.0 provides
| me with a Jython debugger &c...?-)

No, not yet. The debugger should provide a way (hook) to jump to the
source in an editor, using an existing editor process if it is already
running.

| > 6.0 is nearly finished and has some really cool new features including
| > "folding" (the ability to collapse a block of text into a single line
| > on the display).
|
| Cool indeed (I'm sure the EMACSers are laughing at us of course:-).

One of my coworkers who uses emacs said "Emacs has had that for 10
years!" :-). The funny thing is vim has hardly been around that long.

-D


David Bolen

unread,
Jun 7, 2001, 9:15:34 PM6/7/01
to
"Alex Martelli" <ale...@yahoo.com> writes:

> > 6.0 is nearly finished and has some really cool new features including
> > "folding" (the ability to collapse a block of text into a single line
> > on the display).
>
> Cool indeed (I'm sure the EMACSers are laughing at us of course:-).

Nah, we don't mind seeing others play catch-up, so we just give a
small knowing smile :-)

--
-- David
--
/-----------------------------------------------------------------------\
\ David Bolen \ E-mail: db...@fitlinxx.com /
| FitLinxx, Inc. \ Phone: (203) 708-5192 |
/ 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \
\-----------------------------------------------------------------------/

Alex Martelli

unread,
Jun 8, 2001, 3:20:49 AM6/8/01
to Don Dwiggins, pytho...@python.org
"Don Dwiggins" <dw...@advancedmp.net> writes:
...
> > I've posted very extensively about it, and how I prefer 'lightweight
> > proxies' instead -- instances that have no state (but rather delegate
> > all state, and possibly all behavior, to a singly-instanced object not
...

> Sorry, I guess I missed those posts.

I apologize for the incomplete reference, but google surely doesn't
make it attractive to refer to their archive, what with their ugly
URI's (there may be a systematic way to simplify them, as there was
for deja, but if so then I haven't found it yet). Anyway (please
remember that each URI is really meant to be on a single line:-)...:

http://groups.google.com/groups?hl=en&lr=&safe=off&ic=1&th=303263c728caff3a,
4&seekm=8s5afj0cov%40news2.newsguy.com#p

http://groups.google.com/groups?hl=en&lr=&safe=off&ic=1&th=90fe81cf878b00fd,
9&seekm=91d23f0jk7%40news1.newsguy.com#p

http://groups.google.com/groups?hl=en&lr=&safe=off&ic=1&th=e61b533755e27c16,
10&seekm=91lhdb0mb%40news1.newsguy.com#p

http://groups.google.com/groups?q=singleton+design+pattern+group:comp.lang.p
ython+author:Alex+author:Martelli&num=20&hl=en&lr=&safe=off&scoring=d&rnum=6
&ic=1&selm=934uei02u7m%40news2.newsguy.com

http://groups.google.com/groups?q=singleton+design+pattern+group:comp.lang.p
ython+author:Alex+author:Martelli&num=20&hl=en&lr=&safe=off&scoring=d&rnum=4
&ic=1&selm=9bpdsv026s8%40news1.newsguy.com

http://groups.google.com/groups?hl=en&lr=&safe=off&ic=1&th=6caf333bec7f9aef,
7&seekm=9c48mn020mv%40news1.newsguy.com#p

Far from exhaustive, of course, but reasonably representative
of what I've posted on this subject to this newsgroup in last
October, December, April.

I've argued elsewhere about SDP being best not used in other
different contexts (COM, C++, Java) -- the reasons are slightly
different in each case, but some (inappropriate resistance to
design-constraint changes for the SDP, for example) apply
rather widely.


> From the above, it sounds like you
> still start with an SDP-style singleton

Maybe, but not necessarily. Since the singly-instantiated-object
and its instantiation mechanisms are not exposed, but rather are
normally internal implementation details within a single module,
it's relatively irrelevant what (if any!) mechanisms are being
used here. I don't see, offhand, what advantages SDP would bring
in this specific case wrt more trivial just-instantiate-once
approaches to single-instantiation -- no SDP forces are really
in play. If there was an SDP _already_ exposed from somewhere
in a library/framework that I couldn't touch, then I could hide
it behind proxies, of course -- but the SDP, if there, is just
an irrelevant minor annoyance in this case. If the framework
or library had no single-instantiation constraint I might just
as perfectly-well instantiate just once and use the proxies in
exactly the same way.


> for the proxies to "point at", then
> add the LWP class for users to instantiate; this is essentially a Bridge,
> which fits your description of the advantages -- you allow the "state
> package" to be changed while not affecting the clients and, as you also
> describe, you can evolve the LWP separately (e.g., subclassing). It looks
> to me as though, rather than replacing one pattern with another, you've
> created a nice composition of two patterns. Of course, your LWPs, being
> Featherweights, could be used in other ways as well.

I disagree, because the SDP *is* all about exposing the 'single
instance' constraint to client-code -- when client code becomes
supposed to NOT see/access the singly-instantiated-object directly,
but rather only through proxies, what does SDP buy any more?

I do agree that the applicability of featherweight proxies is
very wide -- more generally, I see this as a special case of
a general technique (which Python facilitates wonderfully well,
but is well applicable elsewhere too, and *particularly* apt
in COM for example): decoupling object identity, object state, and
object behavior. State and behavior are (mostly) still seen as
'bundled' when looked at from client-code, but objects delegate
all or part of their state to other objects 'behind the scenes'.

The unit of reuse, in such a scenario, is not the single class
but the package (aka category, cluster, area, module, ...) --
I give the classic references to, and a summary of, R. Martin's
"Reuse/Release Equivalence Principle" in the post:

http://groups.google.com/groups?q=unit+reuse+release+author:alex+author:mart
elli&num=20&hl=en&lr=&safe=off&rnum=2&ic=1&selm=9elmp4010u1%40enews2.newsguy
.com

and I don't think I can explain better than he does WHY taking
the class as "the granule of reuse" (or, of design!) is simply
inferior. OO has long been infected with excessively class-
centered thinking, but it's been breaking free of that mindset
for a while now. Maybe the SDP is one aspect of an excessive
reliance on "one class to bind them all"...:-).


Alex

Alex Martelli

unread,
Jun 8, 2001, 5:11:08 AM6/8/01
to
"D-Man" <dsh...@rit.edu> wrote in message
news:mailman.991952533...@python.org...
...

> | > Patterns discussion explaning why Java is _still_ a very low level
> | > language even though it is bytecode-compiled and interpreted.
> |
> | Well, not VERY low...!-). Just lower than Python...
>
> Sometimes (far too often, especially when writing unit tests) Java
> feels very low level.

Nolo contendere re unit tests.

> | GVIM rules (5.8's what I'm using now), but I doubt even 6.0 provides
> | me with a Jython debugger &c...?-)
>
> No, not yet. The debugger should provide a way (hook) to jump to the
> source in an editor, using an existing editor process if it is already
> running.

But what Jython debugger does this...?


> | > 6.0 is nearly finished and has some really cool new features including
> | > "folding" (the ability to collapse a block of text into a single line
> | > on the display).
> |
> | Cool indeed (I'm sure the EMACSers are laughing at us of course:-).
>
> One of my coworkers who uses emacs said "Emacs has had that for 10
> years!" :-). The funny thing is vim has hardly been around that long.

Yep, but vi was -- warts and all, of course, but still, my
fingers are SO happy not to have to dart for multiple modifier
keys, arrowkeys, mice, etc, when I'm doing serious editing!-)


Alex

Emile van Sebille

unread,
Jun 9, 2001, 10:43:47 AM6/9/01
to
To simplify google refs:

Start with http://groups.google.com/groups?ic=1&q=msgid:, then find the
message ID of the message, as per the standard mail headers. For example,
when I hit reply, it shows your message ID as
mailman.991984874...@python.org (toss the protocol
identifier), yielding
http://groups.google.com/groups?ic=1&q=msgid:mailman.991984874.25882.python-
li...@python.org as the Google ref. Other message id markers are seekm and
selm. Applying this to your list of refs gives:

http://groups.google.com/groups?ic=1&q=msgid:8s5afj0cov%40news2.newsguy.com
http://groups.google.com/groups?ic=1&q=msgid:91d23f0jk7%40news1.newsguy.com
http://groups.google.com/groups?ic=1&q=msgid:91lhdb0mb%40news1.newsguy.com
http://groups.google.com/groups?ic=1&q=msgid:934uei02u7m%40news2.newsguy.com
http://groups.google.com/groups?ic=1&q=msgid:9bpdsv026s8%40news1.newsguy.com
http://groups.google.com/groups?ic=1&q=msgid:9c48mn020mv%40news1.newsguy.com
http://groups.google.com/groups?ic=1&q=msgid:9elmp4010u1%40enews2.newsguy.co
m

HTH,

--

Emile van Sebille
em...@fenx.com

---------


"Alex Martelli" <ale...@yahoo.com> wrote in message

news:mailman.991984874...@python.org...
<snipping non-google refs>

Jarno J Virtanen

unread,
Jun 9, 2001, 6:07:55 PM6/9/01
to
Thu, 7 Jun 2001 00:43:57 -0500 (CDT) Glyph Lefkowitz wrote:

> Since we're on the topic; other design patterns that lurk around
> unobtrusively in Python include the "for" keyword, which is really the
> "Observer" pattern, the notion of classes as callable, which is the
> "Factory" pattern universally applied, and the Strategy pattern
> masquerading as first-class functions. Modules moonlight as the "Facade"
> pattern when they're not playing Singleton. Did guido use the time
> machine to get a copy of the GoFBook before he started working on the
> first version of Python, or are Patterns just a transparent attempt to
> cover for chronically inexpressive languages like C++ and Java which can't
> generally implement these mind-numbingly simple constructs in code?
> Inquiring minds want to know.

In this book I'm reading, "Object book" by Koskimies (available in
Finnish only, "Oliokirja"), the author states that Design Patterns are
actually very vague concept and that the whole computer science is for
great deal identifying and abstracting some general "patterns". This
means that, for example in programming languages some form (or pattern,
for that matter) that is used generally is "raised" and so given own
name and construct in the language. Further, he states that for example
data types and control structures (if, else, while, so on) have been
"developed" (or evolved) this way; some decades ago they could have been
called "design patterns". He raises the question of how many and which
design patterns are found in language "core" in the "object oriented
languages of the future" (sounds like the __future__ mechanism to me
;-).

So the essential thing about design patterns is not the concept
of some design pattern itself, but the "know-how" and design
experience which has been collected under the specific title.

I'm not an expert on this subject, but I'm really interested in it and
I'm going to study it in detail once I get other projects done (such as
my graduate thesis :-).

Marcin 'Qrczak' Kowalczyk

unread,
Jun 10, 2001, 3:45:05 PM6/10/01
to
07 Jun 2001 09:49:36 -0700, Don Dwiggins <dw...@advancedmp.net> pisze:

> Use the Singleton pattern when
> - there must be exactly one instance of a class, and it must be
> accessible to clients from a well-known access point.

One in what? In the world? In all runs of the process? In the current
run of the process? In a large subcomputation?

Why would you create an arbitrary scope of life?

> - when the sole instance should be extensible by subclassing, and
> clients should be able to use an extended instance without modifying
> their code.

If subclassing would alter the behavior of the object - what would
happen if several clients alter it in incompatible ways?

Global implicit state rarely makes sense; mainly for interfacing
with the OS and supporting the runtime system of the language. It's
inflexible - with global state you can't take the meaning of the
program and execute it twice in the process, you can't take a part
of the program and execute it in a different context (it's will not
be self-contained), threading may be problematic.

It's nothing wrong when a stateless data is global. For example
function definitions and class definitions are almost always
stateless. Immutable or lazily evaluated data which doesn't depend
on the process environment is stateless. These are fine because
it doesn't matter when it's created and in how many copies - they
statically define the program.

But state, i.e. objects with meaningful identity, should be managed
explicitly. As a quick hack in small scripts it can be convenient to
have a global variable or two, but it's inflexible.

--
__("< Marcin Kowalczyk * qrc...@knm.org.pl http://qrczak.ids.net.pl/
\__/
^^ SYGNATURA ZASTĘPCZA
QRCZAK

Geoffrey Gerrietts

unread,
Jun 11, 2001, 4:32:08 PM6/11/01
to James_...@i2.com, pytho...@python.org
James Althoff <James_...@i2.com> writes:
> From: James_...@i2.com [mailto:James_...@i2.com]

>
> Geoff Gerrietts <ge...@homegain.com> wrote:
> <snip>
> >In Python, I know how to write classes whose instances are
> >other classes.
>
> Do you mean "whose instances are *themselves* classes"? And if
> so, How do you do this?
> (Can you do this in *Python* -- without doing a C extension?)

Yes, I really meant that. :)

This is the "metaclass" facility -- you can get a much more
formal description of how that works from looking at those docs
(and playing with the examples).

To use metaclasses, you need a metaclass and a helper class. Your
code will instantiate the metaclass. Subclasses of the metaclass
will be operated on ('rewritten') by the helper. An example
appears below.

The metaclass feature is not generally useful. It can be useful
in certain very specific cases, especially if you're writing
toolkits -- you can build functionality into your
(meta)superclass that will "subvert" later declarations.

I've appended an example to this message. It's heavily indebted
to the example used in Guido's paper on metaclasses, found at:

http://www.python.org/doc/essays/metaclasses

That's a good place for further reading -- in my experience, the
toughest part about metaclasses was figuring out what happened
where -- the sequence of calls and what role each of the players
played. I've tried to make that as clear as possible in this
example....

Thanks,
--G.

---
Geoff Gerrietts <ge...@homegain.com>
Software Engineer, HomeGain.com
510-655-0800 x4320

#!/usr/bin/python -i

print
print "defining MetaClass"
class MetaClass:
def __init__(self, name, bases, namespace):
""" for creation of class-level instances """
print "Called MetaClass.__init__ for %s" % name

def __call__(self):
""" for creation of instances of instances """
print "Called MetaClass.__call__"
return Helper(self)

print
print "defining Helper"
class Helper:
def __init__(self, meta):
""" invoked from MetaClass.__call__ for inst of inst
"""
self.meta = meta
print "Called Helper.__init__ for ", meta

def bungee(self, *args):
print "Helper.bungee called"

# here we directly instantiate a class by passing it a name, a
# list of base classes, and a namespace. we call
# MetaClass.__init__ just like we'd expect here
print
print "defining MetaInst (instantiating MetaClass)"
MetaInst = MetaClass('MetaInst', (), {})

# here MetaClass.__init__ gets called again! note that the
# __init__ must accept name, bases, namespace or else this
# will flop
print
print "defining MyStuff"
class MyStuff (MetaInst):
def myMethod(self, *args):
print "MyStuff.myMethod called"

# the actual instance of our child class invokes the __call__
# routine on our MetaClass. The instance itself is the return
# value from that __call__.
print
print "instantiating MyStuff"
mine = MyStuff()
print "Class of our instance ", mine.__class__

# now if you've been following me, you'll be thinking that our
# instance 'mine' is an instance of 'Helper' (the return value
# from MetaClass.__call__), so we can call mine.bungee and see
# what we expect.
print
print "calling bungee"
mine.bungee()

# here's the thing that kinda sucks -- unless you've saved the
# class information in MetaClass.__init__ (and you've overridden
# __getattr__ to get at that stored info), you've lost your
# subclass.
print
print "calling myMethod"
mine.mymethod()

# here's a better init:

class BetterMetaClass:
def __init__(self, name, bases, namespace):
self.__name__ = name
self.__bases__ = bases
self.__namespace__ = namespace
# if you want to muck around with the namespace,
# this might be a good place to do it.

def __call__(self):
return BetterHelper(self)

# and here's a Helper that uses it. note that this Helper
# won't look in its own namespace for matches!
class BetterHelper:
def __init__(self, meta):
self.__meta__ = meta

def __getattr__(self, name):
try:
value = self.__meta__.__namespace__[name]
except KeyError:
raise AttributeError, name
return value

Martijn Faassen

unread,
Jun 14, 2001, 9:47:25 AM6/14/01
to
Alex Martelli <ale...@yahoo.com> wrote:
> "Glyph Lefkowitz" <gl...@twistedmatrix.com> wrote in message
> news:mailman.991892413...@python.org...
>>
>> On 6 Jun 2001, Chris Goringe wrote:
>>
>> !snip!
>>
>> > python doesn't [have ...]
>> > strong typing (love it or hate it...)
>>
>> Hate it :)

> What _I_ hate is the confusion between weak vs strong typing
> AND static vs dynamic typechecks, though it's a classic one:-).
> Weak typing, properly, is what (e.g.) Perl has, where you can
> use any scalar wherever, and it will try to guess what you
> mean, freely treating strings as numbers, viceversa, etc.
> What Python has (like, say, Scheme) I'd call strong typing
> that is dynamically enforced.

I always see this but I'm a bit skeptical about it. Python doesn't really
do any type checking for class instances; it checks whether there is a
method that is of the right name and has the right amount of arguments
somewhere on the instance or its superclasses, and calls it if so. There is
no 'is this the expected class?' check anywhere, not even at runtime.
You can make the same case for built-in types.

*Some* methods of types and classes do a class/type check, of course. Strings
and integers decide to give up if they're __add__-ed to each other, but
that could be considered a feature of the extension module (okay, they're
important ones), not of the language. It certainly doesn't have to be
that way. Python itself doesn't care one way or the other. I think saying
"Python is strongly typed" can be misleading and confusing. "Strongly typed"
and "Dynamically typed" combined doesn't seem to make much sense, if
that language allows users to create their own types/classes.

> E.g.:

> D:\py21>python
> Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license" for more information.
> Alternative ReadLine 1.4 -- Copyright 2001, Chris Gonnerman
>>>> "ciao"[1.0]
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> TypeError: sequence index must be integer
>>>>

> That's *WEAK* typing?! I call it pretty strong indeed --
> and love it! (Java works similarly here -- it's an
> error to use a non-integer as array index -- although
> C and C++ happily accept the float and truncate it...).
> It's *DYNAMICALLY* checked and enforced, not statically.

But only in a few places, mostly for built-in types. Those happen to be the
*important* places but any other checking you'll have to come up
with yourself. I don't think 'call this method can see whether you
succeed' strongly typed.



> I think it's more precise and useful to draw the
> distinction as static vs dynamic than as strong
> vs weak, no matter which way one wants to argue
> for or against it.

That is true; strong versus weak is more a feature of the actual
classes (types) you're using in a dynamically typed language than a feature
of the language itself.

Anyway, I've done my bit to counter the 'Python is strongly typed' meme.
I suspect that meme is around because there are lingering ideas that
strong type checking is a Good Thing. I think some run-time type or
interface checking can be a good thing. But I'd hardly call what Python
is doing 'strong'.

Python has a TypeError exception that methods can raise, and
many methods of built-in objects do this because guessing would be
'magic'.

Regards,

Martijn
--
History of the 20th Century: WW1, WW2, WW3?
No, WWW -- Could we be going in the right direction?

Fernando Pereira

unread,
Jun 16, 2001, 11:35:01 PM6/16/01
to
> Did guido use the time
> machine to get a copy of the GoFBook before he started working on the
> first version of Python, or are Patterns just a transparent attempt to
> cover for chronically inexpressive languages like C++ and Java which can't
> generally implement these mind-numbingly simple constructs in code?
You just answered your own question, didn't you?

-- F

Tim Peters

unread,
Jun 17, 2001, 7:43:48 PM6/17/01
to pytho...@python.org
[Martijn Faassen]
> ...

> Python doesn't really do any type checking for class instances; it
> checks whether there is a method that is of the right name and has
> the right amount of arguments somewhere on the instance or its
> superclasses, and calls it if so. There is no 'is this the expected
> class?' check anywhere, not even at runtime.

If I do

instance.xyz()

and it succeeds, then xyz is necessarily known to instance's class (whether
directly or via a base class). What else is there *to* check in that case?

Try fooling it instead:

class A:
def xyz(self):
print "A.xyz"

class B:
def xyz(self):
print "B.xyz"

a = A()
B.xyz(a)

and you'll discover that Python refuses to run B.xyz() with an instance of
A, even though A has a method of the same name and signature: "is this the
expected class?" checks are done at runtime.


0 new messages