473,387 Members | 1,536 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

python without OO

Is it possible to write purely procedural code in Python, or the OO
constructs in both language and supporting libraries have got so
embedded that it's impossible to avoid them? Also, is anyone aware of
any scripting language that could be considered as "Python minus OO
stuff"? (As you can see I'm completely new to Python and initially
believed it's a nice&simple scripting language before seeing all this
OO stuff that was added in over time)
Thanks,
Davor

Jul 18 '05 #1
63 5051
Davor wrote:
Is it possible to write purely procedural code in Python, or the OO
constructs in both language and supporting libraries have got so
embedded that it's impossible to avoid them?


Hmmm... sorta depends on how you define write procedural code... If
you mean, can you write Python code without accessing object attributes
(e.g. lst.sort()), then the answer's probably almost certainly no. If
you mean can you write Python code without ever writing a class, the
answer's probably yes. It'll make some things harder, and it'll
probably make some modules off-limits, but it's doable.

Could you clarify what you mean by "write purely procedural code"?

Steve
Jul 18 '05 #2
Davor wrote:
Is it possible to write purely procedural code in Python, or the OO
constructs in both language and supporting libraries have got so
embedded that it's impossible to avoid them?
Sure, but you will got problem with libraries. Some of them are in fact
frameworks and need some subclassing or other OO fluff.
Also, is anyone aware of
any scripting language that could be considered as "Python minus OO
stuff"? (As you can see I'm completely new to Python and initially
believed it's a nice&simple scripting language before seeing all this
OO stuff that was added in over time)


Icon, the language for OO haters.

May I ask why you do you hate OO so much?

--
Jarek Zgoda
http://jpa.berlios.de/ | http://www.zgodowie.org/
Jul 18 '05 #3
"Davor" <da*****@gmail.com> wrote in message
news:11*********************@c13g2000cwb.googlegro ups.com...
Is it possible to write purely procedural code in Python, ... Of course!
or the OO
constructs in both language and supporting libraries have got so
embedded that it's impossible to avoid them?
You can always *write your own* purely procedure code.
A tougher problem would be living without the wealth of supporting library
code that is written OO.
Also, is anyone aware of
any scripting language that could be considered as "Python minus OO
stuff"? Anyone aware? Not I!
(As you can see I'm completely new to Python and initially
believed it's a nice&simple scripting language before seeing all this
OO stuff that was added in over time)


Over time ???
Someone can correct me if I'm wrong but I do believe that all that dirty,
rotten OO stuff was incorporated in the language right from the start.
But
If you can live without coding OO, you can do it in Python.

I'm not sure what it is, exactly, you are trying to avoid.
Much "nice&simple scripting " simply has no need to create and use objects.
Of course, the entire structure of Python and all of it's built in data
structures are object oriented. But, if you wish to live within the
confines of your own strictly procedural code, I don't think you need to
deal with the issue.

On the other hand, this does beggar for a reason to bother with Python at
all. It seems you could be happy doing BASH scripts for Linux or DOS batch
files for Windows. Both are "nice&simple" scripting languages free of
object oriented contamination.

Why would you use an object oriented language if you don't want to?
Thomas Bartkus

Jul 18 '05 #4
Thanks,

I do not hate OO - I just do not need it for the project size I'm
dealing with - and the project will eventually become open-source and
have additional developers - so I would prefer that we all stick to
"simple procedural" stuff rather than having to deal with a developer
that will be convincing me that his 50 layers inheritance hierarchy is
good since it exists in some weird pattern that he saw somewhere on
some Java design patterns discussion board :-) and other "proper" OO
design issues... Once I opted for C++ in a very small project and
believed everyone will stick with C subset + better type checking
offered through C++ - but I simply could not manage to keep them off
using OO stuff which was just making program more complicated than it
should have been. (note, I am not an experienced developer, nor the
others I'll be working with (even though some think they are:-)), so I
prefer preemptively dealing with issue of everyone showing off their OO
design skills)

Davor

Jul 18 '05 #5
> On the other hand, this does beggar for a reason to bother with Python at
all. It seems you could be happy doing BASH scripts for Linux or DOS batch
files for Windows. Both are "nice&simple" scripting languages free of
object oriented contamination.


not really, what I need that Python has and bash&dos don't is:

1. portability (interpreter runs quite a bit architectures)
2. good basic library (already there)
3. modules for structuring the application (objects unnecessary)
4. high-level data structures (dictionaries & lists)
5. no strong static type checking
6. very nice syntax

so initially I was hoping this is all what Python is about, but when I
started looking into it it has a huge amount of additional (mainly OO)
stuff which makes it in my view quite bloated now... anyhow, I guess
I'll have to constrain what can be included in the code through
different policies rather than language limitations...
Thanks
Davor
Jul 18 '05 #6
Wrap your head around Python, don't wrap the Python around your head!
This is NOT Java, or C++ or C , it IS Python.
Davor wrote:
(note, I am not an experienced developer, nor the
others I'll be working with (even though some think they are:-)) Don't worry we didn't get confused, it was quite clear ;)
Mostly you are just so off base I just say go *READ* and write more
Python, look at the standard library.
You will only see one or two levels of inheritance as the norm and it
is not that difficult.
Also you are telling me you don't have an OO problem, you have a
problem with your managment and communication skills. so I prefer preemptively dealing with issue of everyone showing off their OO design skills)

Work on that micro-management just a little bit more, that gets the
code flowing ;)
hth,
M.E.Farmer

Jul 18 '05 #7
M.E.Farmer wrote:
Wrap your head around Python, don't wrap the Python around your head!
This is NOT Java, or C++ or C , it IS Python.
that's interesting hypothesis that behavior will vary due to the use of
different language - actually most python scripts that I have seen do
not even use OO which is quite understandable (same with perl, php,..)
and I'm not even sure why all these languages have incorporated OO at all...
(note, I am not an experienced developer, nor the
others I'll be working with (even though some think they are:-))


Don't worry we didn't get confused, it was quite clear ;)


:-)
Also you are telling me you don't have an OO problem, you have a
problem with your managment and communication skills.


yeah, it's really tough telling them to write code so I can understand
it without having to know about all these patterns of theirs.

Davor
Jul 18 '05 #8
Davor wrote:
Thanks,

I do not hate OO - I just do not need it for the project size I'm
dealing with - and the project will eventually become open-source and
have additional developers - so I would prefer that we all stick to
"simple procedural" stuff rather than having to deal with a developer
that will be convincing me that his 50 layers inheritance hierarchy is
good since it exists in some weird pattern that he saw somewhere on
some Java design patterns discussion board :-) and other "proper" OO
design issues... Once I opted for C++ in a very small project and
believed everyone will stick with C subset + better type checking
offered through C++ - but I simply could not manage to keep them off
using OO stuff which was just making program more complicated than it
should have been. (note, I am not an experienced developer, nor the
others I'll be working with (even though some think they are:-)), so I
prefer preemptively dealing with issue of everyone showing off their OO
design skills)

Davor

Perhaps pylint (http://www.logilab.org/projects/pylint) or its ilk can help you
enforce a coding style

Michael

Jul 18 '05 #9
Davor wrote:
M.E.Farmer wrote:
Wrap your head around Python, don't wrap the Python around your head!
This is NOT Java, or C++ or C , it IS Python.


that's interesting hypothesis that behavior will vary due to the use of
different language - actually most python scripts that I have seen do
not even use OO which is quite understandable (same with perl, php,..)
and I'm not even sure why all these languages have incorporated OO at
all...


Of course, *all* Python programs (whether you call them scripts or
otherwise) are using objects. Strings, numbers, files, lists,
dictionaries ... they're all objects. You *can't* write a Python program
without objects, but you can do so without a single "class" declaration.

The point that M.E.Farmer was trying to make is that you should not judge OO
by Java or C++. Those languages make OO a burden, with on the one hand
excessive requirements to subclass, and on the othe hand ... well, C++ is
just a burden all round really :)
Richard

Jul 18 '05 #10
On Tue, 25 Jan 2005 15:01:23 -0800, Davor wrote:
Thanks,

I do not hate OO - I just do not need it for the project size I'm
dealing with - and the project will eventually become open-source and
have additional developers - so I would prefer that we all stick to
"simple procedural" stuff rather than having to deal with a developer
that will be convincing me that his 50 layers inheritance hierarchy is
good since it exists in some weird pattern that he saw somewhere on
some Java design patterns discussion board :-)


The difference between Python OO and Java is that Python's *actually
solves problems* instead of creating them.

Given your experience and goals, I'd recommend going ahead with your plan,
but the time will come when the Right Solution is creating a class, and I
strongly recommend that you not avoid it because of the bad taste Java has
legitimately left in your mouth. Odds are, that time will come sooner
rather than later, too.

I'd also recommend spending a bit more time with Python before trying to
lead a project in it. That's general advice not Python-specific, and I
understand that it is also sometimes impractical. However, you will pay
for it one way or another. If nothing else, people who have learned Python
and are capable of contributing valuable code are going to be very turned
off when they submit perfectly reasonable classes to solve problems and
get shot down for being OO.

(For context on my point of view, I offer up
http://www.jerf.org/writings/bowersLaw.html ; trying to create a
completely class-free large project in Python will be possible, but it is
probably inadvisable, as you are throwing away useful tools that you will
probably end up replicating anyhow. What Java teaches about OO is actively
harmful in learning Python and must be unlearned. Java is the new Basic.)
Jul 18 '05 #11
Davor wrote:
[...] what I need that Python has and bash&dos don't is:

1. portability (interpreter runs quite a bit architectures)
2. good basic library (already there)
3. modules for structuring the application (objects unnecessary)
4. high-level data structures (dictionaries & lists)
5. no strong static type checking
6. very nice syntax
But modules, lists, and dictionaries *are* all objects, and one uses
standard object attribute-access behavior to work with them.
so initially I was hoping this is all what Python is about, but when I
started looking into it it has a huge amount of additional (mainly OO)
stuff which makes it in my view quite bloated now...
If you're basing your opinion of OO off of C++ and Java, then it's not
too surprising that you're wary of it. But really, the OO in Python
is as simple and transparent as the rest of the syntax. You don't
need to define your own classes if you don't want to -- it's quite
easy to write modules that contain only simple functions. A trivial
understanding of objects & object attributes is needed to use the OO
portions of the standard library. If you really want, you can still
dictate that your own project's code be strictly procedural (i.e. you
can use objects but not define objects).
anyhow, I guess
I'll have to constrain what can be included in the code through
different policies rather than language limitations...


You mention elsewhere the fear of some developer with a 50-layer
inheritance heirarchy. That's not something that normally happens in
Python. Indeed, one of the tenets of the Zen of Python is that "flat
is better than nested". But more than that, it's just not necessary
to do that sort of thing in Python.

In statically typed languages like C++ and Java, inheritance trees are
necessary so that you can appropriately categorize objects by their
type. Since you must explicitly declare what type is to be used
where, you may need fine granularity of expressing what type a given
object is, which requires complex inheritance trees. In Python, an
object is whatever type it acts like -- behavior is more important
than declared type, so there's no value to having a huge assortment of
potential types. Deep inheritance trees only happen when people are
migrating from Java. ;)

Jeff Shannon
Technician/Programmer
Credit International
Jul 18 '05 #12

"Davor" <da*****@gmail.com> wrote
I do not hate OO - I just do not need it for the project size I'm
dealing with - and the project will eventually become open-source and
have additional developers...
If you think your project is valuable enough to eventually be "Open
Source",
you can bet that one of the first criticisms it will face is that it is not
OO if
it is perceived that there would be any advantage to being so.

If your question is "Can I write useful Python code without writing my
own classes, without creating a class inheritance heirarchy, etc.?" then the
answer is definitely "Yes!" Python has lots of very useful and practical
libraries to allow you to do all sorts of cool things. Many of those
interfaces though are presented in an OO manner (to varying degrees).
so I would prefer that we all stick to
"simple procedural" stuff rather than having to deal with a developer
that will be convincing me that his 50 layers inheritance hierarchy is
good since it exists in some weird pattern that he saw somewhere on
some Java design patterns discussion board :-) and other "proper" OO
design issues...


If your question is "Can I somehow hobble Python so that there are
no objects anywhere and it is not possible for other developers to even
think about creating something I can't understand?" then I would ask
how is it you are leading a team of other programmers that is apparently
not afraid of OO concepts?

You can write lot's of code that is just functions, and have functions
call other functions, but what does a 'def' statement (python's syntax
for function definition) do? It instantiates a function object. That
function
can be copied (well, the reference to it, anyway), passed to other
functions,
returned from functions, stored in variables, etc. You may or may not see
any practical use for that, but Python was (very wisely) designed to be
OO right from the very start - it definitely wasn't something that was
added on later. You might want to spend a little time pondering why that is.

If you don't understand the difference between pop(mylist) and
mylist.pop(), it would be a wise career move to invest a little time to
understand
what the difference is and why the state of software development has come
to prefer one over the other.

At the bottom, practically everything in Python is an object...
dir(42)

['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__',
'__delattr__', '__div__', '__divmod__', '__doc__', '__float__',
'__floordiv__', '__getattribute__', '__hash__', '__hex__', '__init__',
'__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__',
'__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__',
'__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__',
'__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__',
'__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__',
'__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__',
'__truediv__', '__xor__']

there's just no getting around it. If you want to set down
the groundrules for your project that you will stick to basically just
procedural
code, fine - that's a project management issue. If you are insistent there
can
be no objects anywhere in your implementation, Python is definitely the
WRONG choice. Well... there is no choice. It would be impossible with
Python. Note also that Perl is definitely out, as is JavaScript and even
PHP.
ANSI C might work and (as pointed out earlier), some other likely candidates
are sh, bash, csh, ksh... I don't know a lot about Tcl/Tk - I think it
implements
some rather OO'ish stuff, but worth consideration.

Good luck.
-ej
Jul 18 '05 #13
Davor wrote:
M.E.Farmer wrote:
Wrap your head around Python, don't wrap the Python around your head!
This is NOT Java, or C++ or C , it IS Python.

that's interesting hypothesis that behavior will vary due to the use of
different language ...


If using a different language doesn't require/encourage different
programming habits, then what's the point of using a different language?

"A language that doesn't affect the way you think
about programming, is not worth knowing."
--Alan Perlis

Different languages offer different modes of expression, different
ways of approaching the same problem. That's *why* we have so many
different programming languages -- because no single approach is the
best one for all problems, and knowing multiple approaches helps you
to use your favored approach more effectively.

Jeff Shannon
Technician/Programmer
Credit International

Jul 18 '05 #14
Davor,
I was gonna let it go but .... I never was good at shutin up ;)
The greatest strength a manager can have is delegation. And with that
add the ability to best use the resources available .
It seems you are telling me that :
1) You do not understand most programming concepts
2) You are not willing to learn.
3) You might not have the skill set to manage developers
What does it all mean?
Stop telling your programmers how to program! Seriously NOW.
If you managed a group of doctors would you tell them that they could
only use techniques that *YOU* understood, even if the were STANDARD
and well known by others?
That brings me to the other point , you have mentioned design patterns,
did YOU read GOF Design Patterns? It seems to me that if you were to
spend a week with the book you could grasp at least the gist of the
major patterns.They are pretty simple and quite informative.
You should at least speak the lingo of the field you manage in.
If your guys occasionally do something and you feel lost, that is a
sign you are normal.
Oh yea and don't confuse programming idioms of various language with
design patterns.
Start cultivating a talent for setting clear goals and clear objectives
, learn how to manage people and have better communication (that is two
way) with your developers.
Your job is to be a manager , so __manage__ your team , have the
overview have the design concept have the long road in mind and then at
the same time listen to your team and do what it takes to smooth the
rough edges and move the project forward, don't fiddle the details
unless needed.
Set goals not details unless they are real restrictions. Life is full
of real restrictions and so are most projects so avoid getting into the
unrealistic and unreasonable. Let your talent make you look good and
help them do it.
This advice holds true for every field I can think of. Ignorance can be
remedied with a book , but apathy sometimes needs a swift kick in the
ass.

Hope you do well,
M.E.Farmer

Jul 18 '05 #15
even if I follow the other answers above - language-wise and
management-advise-wise - just for the sake of completeness - I would
like to point you to Lua: http://www.lua.org/

1. portability (interpreter runs quite a bit architectures)
=> yes, nearly pure ANSI-C should compile

2. good basic library (already there)
=> you might have to collect some additional libraries and add them to
the core language, so currently not the strongest part, but typical file
handling is possible (at least w/ luafilesystem module)

3. modules for structuring the application (objects unnecessary)
=> yes, starting w/ current in-work release

4. high-level data structures (dictionaries & lists)
=> just one that combines both dictionary and list

5. no strong static type checking
=> yes

6. very nice syntax
=> little bit more "classic" than Python by using 'then ..end' and the
like, as long as you don't exploit the built-in flexibility of Lua it is
very easy to be read and written.
know what's funny: in the Lua mailing list there is currently a
discussion about adding OO to Lua.
Jul 18 '05 #16
M.E.Farmer,

first to clarify few things - I'm neither manager nor professionally
involved in code development - I'm just embarking on a small project
that I would like to attract some programmers to later on and make it a
nice open-source system. Based on my previous experience with few SMALL
projects, I would like to avoid object orientation as much as possible.
The reason is that I always ended up working with people who were
without much experience, same as me, but they were all so influenced by
OO propaganda that it was impossible to reason with them and to go with
as simple solution as possible (not saying that OO solution is
necessarily more complex than a structured one IN ALL CASES - but in
any single case I've seen so far it was). So every single time I was
wasting time trying to explain why not to go with cool OO way as
opposed to simple un-cool structured solution. So, if the application
was feasible to develop in C or C++, the solution would be easy - just
choose C and avoid all OO mess - of course would have slightly more
problems with C's looser type-checking but in my experience it's far
less problem then troubles that happen when one starts going crazy with
C++ generic classes, multiple inheritance, deep inheritance trees,
etc.. The nature of the application that I'm planning on is perfectly
suited to a good high-level scripting language, and python looked very
attractive so I decided to take look at it, but then i realized it has
all this OO stuff that I got scared off immediately :-) - luckily some
of these other guys including yourself mentioned that there are not
that many issues with Python's OO stuff as there is with Java's of C++
(seems I'm not the only one with Java&C++ OO traumas :-)) - so I'm
encouraged to proceed with Python.
It seems you are telling me that :
1) You do not understand most programming concepts
not really - I rather want to prevent incorporation of anything that is
not really needed in the code...
2) You are not willing to learn.
more that I like to reject anything that is not obviously substantiated
and that many people seem to have problems with...
3) You might not have the skill set to manage developers
maybe not good management approach but I would always opt for "not
giving them the tools I don't want them to use" over "giving them
tools I don't want them to use and then forbidding them to use these
tools" - especially if they are not getting paid for what they are
building :-)
Stop telling your programmers how to program! Seriously NOW.
If you managed a group of doctors would you tell them that they could
only use techniques that *YOU* understood, even if the were STANDARD
and well known by others?


This sounds like one of those ideas preached by agile community - I say
set up the rules and conventions as much as you can (in a
*non-intrusive* way) if you are a manager... Exactly the group of
professionals you mentioned in your example is support for what I am
claiming. In fact in that profession everything is exactly about the
rules, precise techniques, and exact processes that have to be done and
when they have to be used. If anything gets done outside of recommended
practices they are legally responsible for. For example, if a person
has to undergo sinus surgery and the endoscopic version is sufficient
(simple, non-intrusive, internal incision) and a doctor decides to do
the traditional surgery with external cutting - I guess everyone would
be pissed off - especially the patient :-)..

Also, yes, I have read GOF book... but I never found it a big deal -
no one ever had to document structured patterns - which definitely
exist - but seem to be obvious enough that there is no need to write a
book about them...

Thanks for your feedback!
Davor

Jul 18 '05 #17
thanks for the link
know what's funny: in the Lua mailing list there is currently a
discussion about adding OO to Lua.


I guess most of these newer languages have no choice but to support OO
if they want to attract a larger user base :-(...

davor

Jul 18 '05 #18
Davor, Before I learned Python, I too was put off by OO hype. And I
suppose I still would be if I still listened to it. But Python's class
statement is somewhere inbetween a C typedef and C++/Jave classes.
Stripped down pretty much to the essentials and only used when really
useful, it made more sense to me.

If you start a project in Python and enlist other competant Pythoneers,
they most likely will not be OO fanatics. Simply tell prospective partners
that you prefer structured procedural programming to user-written object
classes everywhere. An OO afionado will realise that yours is not the
project to join.

I think you should perhaps read and write more Python code before making a
decision. Do note that methods within a class are functions first and
benefit from good procedural-code-writing ability.

Terry J. Reedy

Jul 18 '05 #19
Davor wrote:
thanks for the link

know what's funny: in the Lua mailing list there is currently a
discussion about adding OO to Lua.

I guess most of these newer languages have no choice but to support OO
if they want to attract a larger user base :-(...


Tell me, have you ever defined a C structure, and then written various functions
to operate on that structure (i.e. taking a pointer to the structure as their
first argument)?

Have you then put both the structure definition and the function prototypes into
a single header file and used that header file from other code?

That's OO programming: associating several pieces of information as an 'object',
and associating various methods to operate on instances of those objects.

Everything else is optional.

Problems with OO design generally result from violations of the KISS principle,
not from OO itself (although languages like Java and C++ make it hard to avoid
violating KISS, since they make you jump through so many hoops to get anything
to work at all). KISS (and the XP mantra "Do the simplest thing that could
possibly work") are the best means to fight off overengineering, rather than a
blanket ban on OO techniques.

Jeremy's "Bower's Law" page really does provide a good perspective on the
benefits of judicious use of OO techniques
(http://www.jerf.org/writings/bowersLaw.html).

Cheers,
Nick.

--
Nick Coghlan | nc******@email.com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
Jul 18 '05 #20
Davor <da*****@gmail.com> wrote:
no one ever had to document structured patterns - which definitely
exist - but seem to be obvious enough that there is no need to write a
book about them...


You _gotta_ be kidding -- what do you think, e.g., Wirth's "Algorithms
plus Data Structures Equals Programs" *IS* all about?
Alex
Jul 18 '05 #21
I can't resist to point here to the
Re: How to input one char at a time from stdin?
posting in this newsgroup to demonstrate, what
this thread is about.

Claudio
On Tue, 25 Jan 2005 12:38:13 -0700, Brent W. Hughes
<br**********@comcast.net> wrote:
I'd like to get a character from stdin, perform some action, get another character, etc. If I just use stdin.read(1), it waits until I finish typing a whole line before I can get the first character. How do I deal with
this?
This is exactly what you need:
http://aspn.activestate.com/ASPN/Coo.../Recipe/134892
Title: "getch()-like unbuffered character reading from stdin on both
Windows and Unix"
Nice to know how, but all those double underscores made my eyes bleed.
Three classes? What's wrong with something simple like the following
(not tested on Unix)?
import sys
bims = sys.builtin_module_names
if 'msvcrt' in bims:
# Windows
from msvcrt import getch
elif 'termios' in bims:
# Unix
import tty, termios
def getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
else:
raise NotImplementedError, '... fill in Mac Carbon code here'


"Davor" <da*****@gmail.com> schrieb im Newsbeitrag
news:11*********************@c13g2000cwb.googlegro ups.com... Is it possible to write purely procedural code in Python, or the OO
constructs in both language and supporting libraries have got so
embedded that it's impossible to avoid them? Also, is anyone aware of
any scripting language that could be considered as "Python minus OO
stuff"? (As you can see I'm completely new to Python and initially
believed it's a nice&simple scripting language before seeing all this
OO stuff that was added in over time)
Thanks,
Davor


Here the OO "solution" (activestate recipe 134892):

class _Getch:
"""Gets a single character from standard input. Does not echo to the
screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()

def __call__(self): return self.impl()
class _GetchUnix:
def __init__(self):
import tty, sys

def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class _GetchWindows:
def __init__(self):
import msvcrt

def __call__(self):
import msvcrt
return msvcrt.getch()
getch = _Getch()
Jul 18 '05 #22
It's perfectly possible to write good python code without using
classes. (and using functions/normal control flow).

You will have a problem with terrminology though - in python everything
is an object (more or less). Common operations use attributes and
methods of standard objects.

For example :
somestring = 'fish'
if somestring.startswith('f'):
print 'It does'


The above example uses the 'startswith' method of all string objects.

Creating your own 'classes' of objects, with methods and attributes, is
just as useful.

You can certainly use/learn python without having to understand object
oreinted programming straight away. On the other hand, Python's object
model is so simple/useful that you *will* want to use it.
Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

Jul 18 '05 #23
On 25 Jan 2005 13:49:48 -0800, Davor <da*****@gmail.com> wrote:
Is it possible to write purely procedural code in Python, or the OO
constructs in both language and supporting libraries have got so
embedded that it's impossible to avoid them? Also, is anyone aware of
any scripting language that could be considered as "Python minus OO
stuff"? (As you can see I'm completely new to Python and initially
believed it's a nice&simple scripting language before seeing all this
OO stuff that was added in over time)
Thanks,
Davor
Umm, just curious -- why would you want to not use the OO stuff?
Python is like pseudocode (the basic OO, which is mostly common to
most OO languages, isn't really complicated).

Moreover, using Python without OO would be like, um, eating mango seed
without the pulp. :)

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

--
Premshree Pillai
http://www.livejournal.com/~premshree
Jul 18 '05 #24
Hello Davor,
Also, is anyone aware of any scripting language that could be considered
as "Python minus OO stuff"?

Maybe Lisp (http://clisp.cons.org/, http://www.paulgraham.com/onlisp.html)
or Scheme (http://www.plt-scheme.org/software/mzscheme/,
http://mitpress.mit.edu/sicp/full-text/book/book.html)
will be better for you mind :-)

HTH.
--
------------------------------------------------------------------------
Miki Tebeka <mi*********@zoran.com>
http://tebeka.bizhat.com
The only difference between children and adults is the price of the toys
Jul 18 '05 #25
Davor wrote:
Is it possible to write purely procedural code in Python, or the OO
constructs in both language and supporting libraries have got so
embedded that it's impossible to avoid them? Also, is anyone aware of
any scripting language that could be considered as "Python minus OO
stuff"? (As you can see I'm completely new to Python and initially
believed it's a nice&simple scripting language before seeing all this
OO stuff that was added in over time)
Thanks,
Davor

Hello,

Yes you can, that is a benefit and flaw of python in that you
can mix up procedural and OO code, it allows for simple solutions -
however it also allows for you to create all kinds of havoc. IMHO,
there would have to be a very very small task to require procedural
code. Especially if the code is gonna be open sourced (and presumably
built upon) you will benefit from a proper design so that it can be
developed and moved on in the future.

One other thing, if your developers are proposing deep inheritance
trees in _any_ language then they are designing incorrectly. In none of
the languages I code in would I design a deep inheritance tree, the deep
inheritance tree is a fault of the designer not the language (for
example Java does not force you to design deep inheritance trees!) - 90%
of the time. I say this because you do need to be aware of the
'mythical python wand' which will turn you from a bad programmer into a
good programmer simply by typing 'class Klass(object):'.

Rather than reading a GOF book, I'd pick up an introduction to OO
programming book to take a refresher course - you thank yourself!!

Language without OO at all - what about Logo - drive that little
tortoise around!!

Cheers,

Neil

Jul 18 '05 #26
Davor schrieb:
so initially I was hoping this is all what Python is about, but when I
started looking into it it has a huge amount of additional (mainly OO)
stuff which makes it in my view quite bloated now.


So you think f.write('Hello world') is bloated and file_write(f,'Hello world')
is not? This is the minimum amount of OO you will see when using Python. But
I guess you will use OO in the long run to *avoid* bloated code:

--------------snip---------------

print "*** Davor's evolution towards an OO programmer ***"

print '\n*** Step 1: OO is evil, have to use atomic variables:'

name1 = 'Smith'
age1 = 35
sex1 = 'male'
name2 = 'Miller'
age2 = 33
sex2 = 'female'

print name1, age1, sex1, name2, age2, sex2

print '\n*** Step 2: This is messy, put stuff in lists:'

p1 = ['Smith', 35, 'male']
p2 = ['Miller', 33, 'female']

for e in p1:
print e

for e in p2:
print e

print '\n*** Step 3: Wait ..., p[2] is age, or was it sex? Better take a dict:'

p1 = dict(name = 'Smith', age = 35, sex = 'male')
p2 = dict(name = 'Miller', age = 33, sex = 'female')

for e in p1.keys():
print '%s: %s' % (e, p1[e])

for e in p2.keys():
print '%s: %s' % (e, p2[e])

print '\n*** Step 4: Have to create person dicts, invoice dicts, ...better use dict templates:'

class printable:
def __str__(self):
'''magic method called by print, str() ..'''
ps = ''
for e in self.__dict__.keys():
ps += '%s: %s\n' % (e, str(self.__dict__[e]))
return ps

class person(printable):
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex

class invoice(printable):
def __init__(self, name, product, price):
self.name = name
self.product = product
self.price = price

per = person(name = 'Smith', age = 35, sex = 'male')
inv = invoice(name = 'Smith', product = 'bike', price = 300.0)

print per
print inv

--------------snip---------------

Either your program is small. Then you can do it alone. Or you will
reach step 4.

--
-------------------------------------------------------------------
Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0
E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64')
-------------------------------------------------------------------
Jul 18 '05 #27

"Davor" <da*****@gmail.com> wrote in message
news:ct**********@rumours.uwaterloo.ca...
On the other hand, this does beggar for a reason to bother with Python at all. It seems you could be happy doing BASH scripts for Linux or DOS batch files for Windows. Both are "nice&simple" scripting languages free of
object oriented contamination.
not really, what I need that Python has and bash&dos don't is:

1. portability (interpreter runs quite a bit architectures)
2. good basic library (already there)
3. modules for structuring the application (objects unnecessary)
4. high-level data structures (dictionaries & lists)
5. no strong static type checking
6. very nice syntax

so initially I was hoping this is all what Python is about, ...


The irony here is that the OO approach woven into the warp and woof of
Python is what make 1-6 possible.
but when I
started looking into it it has a huge amount of additional (mainly OO)
stuff which makes it in my view quite bloated now...
Again, there is nothing "additional" about the OO in Python. It is the very
foundation upon which it is built.
... anyhow, I guess
I'll have to constrain what can be included in the code through
different policies rather than language limitations...

It would be reasonable to decide that Python is not what you are looking
for.
I'm not sure that castrating it in this manner would be quite so reasonable.

Thomas Bartkus
Jul 18 '05 #28

Peter Maas wrote:
Davor schrieb:
so initially I was hoping this is all what Python is about, but when I started looking into it it has a huge amount of additional (mainly OO) stuff which makes it in my view quite bloated now.
So you think f.write('Hello world') is bloated and

file_write(f,'Hello world') is not? This is the minimum amount of OO you will see when using Python. But I guess you will use OO in the long run to *avoid* bloated code:

--------------snip---------------

print "*** Davor's evolution towards an OO programmer ***"

print '\n*** Step 1: OO is evil, have to use atomic variables:'

name1 = 'Smith'
age1 = 35
sex1 = 'male'
name2 = 'Miller'
age2 = 33
sex2 = 'female'

print name1, age1, sex1, name2, age2, sex2

print '\n*** Step 2: This is messy, put stuff in lists:'

p1 = ['Smith', 35, 'male']
p2 = ['Miller', 33, 'female']

for e in p1:
print e

for e in p2:
print e


Being a Fortranner, my "Step 2" would be to use parallel arrays:

names = ['Smith','Miller']
ages = [35,33]
sexes = ['male','female']

for i in range(len(names)):
print names[i],ages[i],sexes[i]

There are disadvantages of parallel arrays (lists) -- instead of
passing one list of 'persons' to a function one must pass 3 lists, and
one can unexpectedly have lists of different sizes if there is a bug in
the program or data file. But there are advantages, too. Sometimes one
does not need to pass the entire data set to a function, just one
attribute (for examples, the ages to compute the average age). This is
more convenient with parallel arrays than a list of objects (although
it's easy in Fortran 90/95).

I am not saying that parallel arrays are better than classes for
storing data, just that they are not always worse.

It is a strength of Python that like C++, it does not force you to
program in an object-oriented style. Lutz and Ascher, in the 2nd
edition of "Learning Python", do not mention OOP for almost the first
300 pages. They say (p297)

"Python OOP is entirely optional, and you don't need to use classes
just to get started. In fact, you can get plenty of work done with
simpler constructs such as functions, or even simple top-level script
code. But classes turn out to be one of the most useful tools Python
provides ..."

Jul 18 '05 #29

"Peter Maas" <pe***@somewhere.com> wrote in message
news:ct**********@swifty.westend.com...
Davor schrieb:
so initially I was hoping this is all what Python is about, but when I
started looking into it it has a huge amount of additional (mainly OO)
stuff which makes it in my view quite bloated now.
So you think f.write('Hello world') is bloated and file_write(f,'Hello
world')
is not? This is the minimum amount of OO you will see when using Python.


Now that we have gently teased Davor for his OO fear, I think we should
acknowledge that his fears, and specifically his bloat fear, are not
baseless.

In Python, one can *optionally* write a+b as a.__add__(b). That is bloat.
I believe, in some strict OO languages, that bloat is mandatory. For one
operation, the bloat is minor. For ever a relatively simple expression
such as b**2-4*a*c, it becomes insanity.

If we were to have to write sin(x) instead as x.sin(), there would not be
syntax bloat. And it would be easier to write generic float-or-complex
math functions, just as your print example shows how __str__ methods
facilitate generic print operations. But if the class method syntax were
manditory, there would be class and/or class hierarchy bloat due to the
unlimited number of possible functions-of-a-float and large number of
actual such functions that have been written.

On the other hand... curryleft(list.append, somelist) is a bit more to type
than somelist.append.
print "*** Davor's evolution towards an OO programmer ***"


Your Four Steps to Python Object Oriented Programming - vars, lists, dicts,
and finally classes is great. It makes this thread worthwhile. I saved it
and perhaps will use it sometime (with credit to you) to explain same to
others.

Terry J. Reedy

Jul 18 '05 #30
Le mercredi 26 Janvier 2005 02:43, Jeff Shannon a écrit*:
In statically typed languages like C++ and Java, inheritance trees are
necessary so that you can appropriately categorize objects by their
type. Since you must explicitly declare what type is to be used
where, you may need fine granularity of expressing what type a given
object is, which requires complex inheritance trees. In Python, an
object is whatever type it acts like -- behavior is more important
than declared type, so there's no value to having a huge assortment of
potential types. Deep inheritance trees only happen when people are
migrating from Java. ;)

Jeff Shannon
Technician/Programmer
Credit International


These lines precisely express my thoughts. Most of the difficulties in OO in
Java/C++ comes from the all mighty goal of preserving type safety. Type
safety is certainly a very desirable goal but it, sometimes, leads to very
complex code only to achieve it. The prize is just too high. The design
patterns that were supposed to save time through high code reuse oftenly
becomes a maintenance nightmare. Something that no one in the company can
understand except a few. Instead of trying to fix some domain specific code,
you end up trying to fix a supposedly highly reusable code that, oh well, you
have to adapt. This is espeacially true if the system had been designed by a
big OO-design-patterns enthusiastic programmer geek.

I am not saying that design patterns are bad. I think that they are an
invaluable gift to OO. I'm only saying that they have indeed a perniciuous
and pervert effect in the real world industry. People become religious about
it and forget to think about a simple solution ...

Being dynamically typed, these kind monster patterns are much less probable.
And the Python philosophy and culture is the very contrary to that trend.

I've been involved in C++/Java projects for the last 8 years. The first time I
met Python, I've been frigthen by its lack of static type safety. But over
the time, I've been convinced by seeing clean Python code over and over
again. In the end, I could appreciate that being simple leads the way to less
bugs, which type safety was supposed to prevent ... Coming from the C++
community, Python had been just like fresh air. It changed me from the
nightmare derscribed in that discussion thread. When I think that comapnies
pay big money for these kind of monsters after having seen a few ppt slides
about it, it makes me shiver.

Regards,

Francis Girard
FRANCE
Jul 18 '05 #31
PA

On Jan 26, 2005, at 20:39, Francis Girard wrote:
When I think that comapnies
pay big money for these kind of monsters after having seen a few ppt
slides
about it, it makes me shiver.


Right... but... since when does an implementation language of any sort
save a project from its own doom?

Project fails for many reasons but seldomly because one language is
"better" or "worst" than another one.

Cheers

--
PA
http://alt.textdrive.com/

Jul 18 '05 #32
Le mercredi 26 Janvier 2005 20:47, PA a écrit*:
Project fails for many reasons but seldomly because one language is
"better" or "worst" than another one.
I think you're right. But you have to choose the right tools that fit your
needs. But I think that's what you meant anyway.

Cheers

Cheers too,

Francis Girard
FRANCE
--
PA
http://alt.textdrive.com/


Jul 18 '05 #33
On Wednesday 26 January 2005 18:55, Terry Reedy wrote:
Your Four Steps to Python Object Oriented Programming - vars, lists, dicts,
and finally classes is great. It makes this thread worthwhile. I saved it
and perhaps will use it sometime (with credit to you) to explain same to
others.


I think so too. M.E. Farmer's reflections on management was also a shining
piece of gold in this thread.
Cheers,

Frans

Jul 18 '05 #34
PA

On Jan 26, 2005, at 21:35, Francis Girard wrote:
Project fails for many reasons but seldomly because one language is
"better" or "worst" than another one.


I think you're right. But you have to choose the right tools that fit
your
needs. But I think that's what you meant anyway.


Yes. But even with the "best" tool and the "best" intents, projects
still fail. In fact, most IT projects are considered failures:

http://www.economist.com/business/Pr...ory_ID=3423238

Cheers

--
PA
http://alt.textdrive.com/

Jul 18 '05 #35
Le mercredi 26 Janvier 2005 21:44, PA a écrit*:
On Jan 26, 2005, at 21:35, Francis Girard wrote:
Project fails for many reasons but seldomly because one language is
"better" or "worst" than another one.
I think you're right. But you have to choose the right tools that fit
your
needs. But I think that's what you meant anyway.


Yes. But even with the "best" tool and the "best" intents, projects
still fail. In fact, most IT projects are considered failures:

http://www.economist.com/business/Pr...ory_ID=3423238


Well, let's go back home for some gardening. My wife will be happy.

Cheers

--
PA
http://alt.textdrive.com/


Jul 18 '05 #36
In <ct*************@news.t-online.com>, Frank Bechmann (w) wrote:
know what's funny: in the Lua mailing list there is currently a
discussion about adding OO to Lua.


From my quick glance at the language last year I recall that one can
access elements of tables (in Python: dict()) with this syntax:
``tbl.attr`` and it's also possible to put functions into those tables. So
it's already a prototype based OO language. Remember: you need objects
for an OO language -- classes are optional!

Ciao,
Marc 'BlackJack' Rintsch
Jul 18 '05 #37
Nick Coghlan wrote:
Davor wrote:
thanks for the link

know what's funny: in the Lua mailing list there is currently a
discussion about adding OO to Lua.

I guess most of these newer languages have no choice but to support OO if they want to attract a larger user base :-(...


Tell me, have you ever defined a C structure, and then written

various functions to operate on that structure (i.e. taking a pointer to the structure as their first argument)?

Have you then put both the structure definition and the function prototypes into a single header file and used that header file from other code?

That's OO programming: associating several pieces of information as an 'object', and associating various methods to operate on instances of those

objects.

Then why was C++ invented? What you have described can be done in C,
Pascal, and Fortran 90, all of which are generally classified as
procedural programming languages. As Lutz and Ascher say in "Learning
Python", in object-based programming one can pass objects around, use
them in expressions, and call their methods. "To qualify as being truly
object-oriented (OO), though, objects need to also participate in
something called an inheritance hierarchy." Whether true OOP is a Good
Thing is arguable and depends on the situation.

Jul 18 '05 #38
This guy has got to be a troll. No other way to understand.

--
Timo Virkkala
Jul 18 '05 #39
Timo Virkkala wrote:
This guy has got to be a troll. No other way to understand.


not really - it was not my intention at all - but it seems people get
upset whenever this OO stuff is mentioned - and what I did not expect at
all at this forum as I believed Python people should not be so OO
hardcore (seems not all as quite a few have indicated in their
replies)... Nevertheless, I think the discussion has several quite good
points!
Jul 18 '05 #40
>>>>> "Davor" == Davor <da*****@gmail.com> writes:

Davor> not really - it was not my intention at all - but it seems
Davor> people get upset whenever this OO stuff is mentioned - and
Davor> what I did not expect at all at this forum as I believed
Davor> Python people should not be so OO hardcore (seems not all
Davor> as quite a few have indicated in their
Davor> replies)... Nevertheless, I think the discussion has
Davor> several quite good points! --
Davor> http://mail.python.org/mailman/listinfo/python-list

Consider the case of a list, say

x = [1,2,3,4]

suppose you wanted to reverse the list, so that x becomes [4,3,2,1].
In a procedural language, one might do

x = reverse(x)

In an OO language such as python, one might do

x.reverse()

Is the OO way more obscure and complicated, etc? Not really -- it's
only a minor syntactical difference. One of the core ideas behind OO
programming is that data (the contents of the list 1,2,3,4) and
methods (sorting, reversing) are bound together into a single entity,
the object. On the face of it, this is rather sensible.

You may rightly recoil against unnecessary abstraction and complexity,
abuse of multiple inheritance and so on. That's perfectly sensible.
But object orientation is probably not the bogey man here. python
values readable code that is as simple as possible (but no simpler!)
as you seem to. Focus on the actual problem, which is probably not OO
programming, but colleagues who are making a design more complex than
need be.

Indeed, the third chant in the mantra of python is "Simple is better
than complex."

John-Hunters-Computer:~> python
Python 2.3 (#1, Sep 13 2003, 00:49:11)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
import this

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Jul 18 '05 #41
I'd like to thank everyone for their replies. The main important lesson
I got is:

Python does not have that many issues with misuse of OO as compared to
Java/C++ because it's *dynamically* typed language and extremely
powerful *dictionary* data structure.

I browsed docs a bit today, and they also confirm what I have believed -
that OO is totally secondary in Python. In fact,
object/classes/metaclasses are nothing but *dictionaries with identity*
in python. Love this approach. In fact, you can very easily implement
your own *OO model* completely separate of Python's OO model... Now I
actually strongly believe that Python's author has introduced the whole
OO model just to attract and make happy OO population... In fact,

*Python's dynamic type checking mechanisms + dictionary is way more
powerful than Java/C++'s static type checking mechanisms + their OO
mechanisms*

and you can definitely be more productive using Python's structured
programming than Java/C++ OO programming :-)... and Python is probably
the best example why we should have skipped OO all together..

---
second, instead of playing with OO plagued design principles do as follows:

1. separate data, functionality, and structure from each other as much
as you can (in Python only valid structural element I've seen so far is
module - ignore objects & classes!)
2. do not assume any have identity (even if the underlying language
model provides and uses one) - so don't pass them around and crazy stuff...

so you get a nice program with separate data structures and functions
that operate on these data structures, with modules as containers for
both (again ideally separated). Very simple to do and maintain no matter
what OO preachers tell you...

Davor
Jul 18 '05 #42
John Hunter wrote:
>> "Davor" == Davor <da*****@gmail.com> writes:


Davor> not really - it was not my intention at all - but it seems
Davor> people get upset whenever this OO stuff is mentioned - and
Davor> what I did not expect at all at this forum as I believed
Davor> Python people should not be so OO hardcore (seems not all
Davor> as quite a few have indicated in their
Davor> replies)... Nevertheless, I think the discussion has
Davor> several quite good points! --
Davor> http://mail.python.org/mailman/listinfo/python-list

Consider the case of a list, say

x = [1,2,3,4]

suppose you wanted to reverse the list, so that x becomes [4,3,2,1].
In a procedural language, one might do

x = reverse(x)

In an OO language such as python, one might do

x.reverse()

Is the OO way more obscure and complicated, etc? Not really -- it's
only a minor syntactical difference. One of the core ideas behind OO
programming is that data (the contents of the list 1,2,3,4) and
methods (sorting, reversing) are bound together into a single entity,
the object. On the face of it, this is rather sensible.


I think the OO way is slightly more obscure. It's obvious what x =
reverse(x) does, but it is not clear unless you have the source code
whether x.reverse() reverses x or if it returns a reversed list. If
x.reverse() does the former, a disadvantage relative to the procedural
approach is that a function can be used in an expression. It is clearer
and more concise to write

z = reverse(x) + reverse(y)

than

x.reverse()
y.reverse()
z = x + y

Furthermore, if in Python the algorithm for the reverse function
applies to many kinds of objects, it just needs to be coded once,
whereas a reverse method would have to provided for each class that
uses it (perhaps through inheritance).

Jul 18 '05 #43
"The object-oriented programming paradigm has an undeserved reputation
as being complicated; most of the complexity of languages such as C++
and Java has nothing to do with their object orientation but comes
instead from the type declarations and the mechanisms to work around
them. This is a prime example of how Scheme's approach of removing
restrictions compares with the "piling feature on top of feature"
needed in other languages, such as the C++ template mechanism."

"Handbook of Programming Languages, Volume IV: Functional and Logic
Programming Languages"
Peter H. Salus, editor
1998
page 63

Similarly, now, Java's generics!

--
Regards,
Casey
Jul 18 '05 #44
>>>>> "beliavsky" == beliavsky <be*******@aol.com> writes:

beliavsky> I think the OO way is slightly more obscure. It's
beliavsky> obvious what x = reverse(x) does, but it is not clear
beliavsky> unless you have the source code whether x.reverse()

You don't need to read the src, you just need to read the docs
help([].reverse)

Help on built-in function reverse:

reverse(...)
L.reverse() -- reverse *IN PLACE*

beliavsky> reverses x or if it returns a reversed list. If
beliavsky> x.reverse() does the former, a disadvantage relative to
beliavsky> the procedural approach is that a function can be used
beliavsky> in an expression. It is clearer and more concise to
beliavsky> write

beliavsky> z = reverse(x) + reverse(y)

The distinction is not OO versus procedural, it is a decision about
how you choose to write "reverse". The python list implementers of
the reverse object method could have decided to return a new reversed
list rather than do the reverse in place and return None. Then you
could have done

z = x.reverse() + y.reverse()

They could have chosen to reverse the list *in place* and also
returned a reference to self rather than None, in which case you could
do the above as well. w/o digging up the transcripts from the
python-dev mailing list, my guess is that they choose to do it in
place for efficiency in memory and cpu, and chose not to return self
to prevent user confusion. Ie, if a user was allowed to do 'z =
x.reverse() + y.reverse()' they might be surprised to find the side
effect of in place modification.

Likewise, I could easily write a procedural "in place" reverse that
returns None, in which case 'z = reverse(x) + reverse(y)' would not do
what you suggest. My point is that whether a function/method such as
reverse operates in place or on a copy, and whether it returns None or
a reference to a list is independent of OO vs procedural style and is
motivated by considerations of efficiency, readability, and usability.

beliavsky> Furthermore, if in Python the algorithm for the reverse
beliavsky> function applies to many kinds of objects, it just
beliavsky> needs to be coded once, whereas a reverse method would
beliavsky> have to provided for each class that uses it (perhaps
beliavsky> through inheritance).

True, a generic reverse procedure/function can be applied to any data
structure that supports iteration. In the case of python, however,
some iterable data structures are mutable (lists, dicts) and some are
not (strings, tuples). For mutable sequences, an in place reverse is
likely to be more efficient in memory and perhaps CPU than a generic
reverse which returns a new copy. So a specialized method "reverse"
applicable to lists (but not strings and tuples) can be a big win.
Fortunately, python supports both, allowing you to define a general
"reverse" that works for any object that supports the sequence
protocol, as well as to define an object specific reverse method that
may be faster in time and space.

JDH

Jul 18 '05 #45
>>>>> "beliavsky" == beliavsky <be*******@aol.com> writes:

beliavsky> I think the OO way is slightly more obscure. It's
beliavsky> obvious what x = reverse(x) does, but it is not clear
beliavsky> unless you have the source code whether x.reverse()
beliavsky> reverses x or if it returns a reversed list.

What make it so clear to you that reverse(x) will always return a
reversed list rather than reversing x in place and return nothing?

beliavsky> It is clearer and more concise to write
beliavsky> z = reverse(x) + reverse(y)
beliavsky> than
beliavsky> x.reverse()
beliavsky> y.reverse()
beliavsky> z = x + y

This isn't anything to do with OO programming. It is something about
using in interface that your audience expects. You have exactly the
same problem whether you are using procedural or OO style. It might
be a case for functional programming, but that's something off-topic.

beliavsky> Furthermore, if in Python the algorithm for the reverse
beliavsky> function applies to many kinds of objects, it just
beliavsky> needs to be coded once, whereas a reverse method would
beliavsky> have to provided for each class that uses it (perhaps
beliavsky> through inheritance).

That the reverse() wants to be a function doesn't mean that the thing
that reverse() operate on doesn't want to be an object. So this isn't
very clear a problem about OO style vs. procedural style, but instead
a problem about "generic" programming style vs. "concrete" programming
style. On the other hand, if the thing that reverse() operate on
isn't an object sharing the same interface, it will be more clumsy to
implement a generic reverse() that works for all the different kinds
of object---even if they share similar interfaces. Try to implement a
generic "reverse" in C when the different type of containers are
encoded as different style struct's accessible from different
function, and you will understand what I mean. So this is,
marginally, a case *for* OO style.

Regards,
Isaac.
Jul 18 '05 #46
On Wed, 2005-01-26 at 22:28 -0500, Davor wrote:
I browsed docs a bit today, and they also confirm what I have believed -
that OO is totally secondary in Python. In fact,
object/classes/metaclasses are nothing but *dictionaries with identity*
in python. Love this approach.


I was really impressed with the design of the language, especially this
bit. I first "got" it when reading Learning Python 2nd Ed (well *after*
I'd been using Python for a while, but it's always good to read even
intro books to fill out "obvious" things you might've missed). I love
the way the same "It's just a dictionary search" principle applies to
inheritance, scoped variable lookups, etc.

In Python, even metaclasses just operate on the class dictionary. How
pleasantly simple :-) - especially how the step from class factory to
metaclass is so small and approachable.

I also love the way I can chuck a bunch of objects into a functionally
styled processing pipeline, say a series of functions that each just
return the result of a listcomp/genexp.

--
Craig Ringer

Jul 18 '05 #47
Davor wrote:
Thanks,

I do not hate OO - I just do not need it for the project size I'm
dealing with - and the project will eventually become open-source and
have additional developers - so I would prefer that we all stick to
"simple procedural" stuff rather than having to deal with a developer
that will be convincing me that his 50 layers inheritance hierarchy is good since it exists in some weird pattern that he saw somewhere on
some Java design patterns discussion board :-) and other "proper" OO
design issues... Once I opted for C++ in a very small project and
believed everyone will stick with C subset + better type checking
offered through C++ - but I simply could not manage to keep them off
using OO stuff which was just making program more complicated than it
should have been. (note, I am not an experienced developer, nor the
others I'll be working with (even though some think they are:-)), so I prefer preemptively dealing with issue of everyone showing off their OO design skills)


I think Davor is making an important point here: Python has grown in
the last 14 years, and it is no more the simple scripting language
it used to be. In particular, it evolved a lot of OOP "cruft"
(static/classmethods, properties, the __new__ method, super, the new
MRO, descriptors,metaclasses, etc.) and there is more than a learning
curve issue coming with the added complexity. Davor is right: even if
you do not want to use it, the stuff is *there* and somebody in your
team will. So definitely there is an audience of programmers that just
do not have an use for all the sophistication and actually are
penalized by it.

There is not much than can be done at the Python level. But I would
see with interest a Python spinoff geared towards simplicity. Few
months ago there was the Prothon proposal (by all means a terrible
proposal) but the goal that motivated it (simplification, trying
to remove classes) was in my opinion worthwhile.

Now, *how* to remove (or simplify) classes is not at all clear to me,
not I am convinced that prototypes are the right way to go, but still I
feel that there is something wrong with inheritance. Maybe
protocols are the solution, who knows? But in any case I think it
is important to keep searching for semplicity. I do not believe
Python is the definitive language, and it is probabily possible
to introduce something better. It is just that nothing of the
kind appeared until now, but I keep watching at the horizon ;)
Michele Simionato

Jul 18 '05 #48
Davor wrote:
Timo Virkkala wrote:
This guy has got to be a troll. No other way to understand.


not really - it was not my intention at all - but it seems people get
upset whenever this OO stuff is mentioned - and what I did not expect at
all at this forum as I believed Python people should not be so OO
hardcore (seems not all as quite a few have indicated in their
replies)... Nevertheless, I think the discussion has several quite good
points!


Yes, sorry about that. I posted too soon. After posting I read more of your
posts and realized that you really mean it, so I tried to cancel my message, but
apparently it got through (news message canceling has never been that reliable..).

I believe that if you take the time to do some Python programming, you can find
out that OO, when used correctly, is not the huge monster your previous
languages had led you to believe it is. In Python, you can use just the right
amount of OO to make things easier and more sensible, without complicating
things with huge inheritance trees and unnecessary polymorphism.

Again, sorry about my premature judgement.

--
Timo Virkkala
Jul 18 '05 #49
be*******@aol.com wrote:
I think the OO way is slightly more obscure. It's obvious what x =
reverse(x) does, but it is not clear unless you have the source code
whether x.reverse() reverses x or if it returns a reversed list. If
x.reverse() does the former, a disadvantage relative to the procedural
approach is that a function can be used in an expression. It is clearer
and more concise to write


Sure, it's clear if in written code you see

x = reverse(x)

To me it would also be clear to see

x.reverse()

But what if you just see in some list that there is a reverse(sequence)
function, or that a sequence has a reverse() method? To me, neither of these is
clear. Do they return a new, reversed sequence or reverse in place?

When creating a new API, I would probably use a convention where reverse does it
in place and reversed returns a new. So, in my API,

reverse(x)
y = reversed(x)
x.reverse()
y = x.reversed()

--
Timo Virkkala
Jul 18 '05 #50

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Andrew Dalke | last post by:
Is there an author index for the new version of the Python cookbook? As a contributor I got my comp version delivered today and my ego wanted some gratification. I couldn't find my entries. ...
68
by: Lad | last post by:
Is anyone capable of providing Python advantages over PHP if there are any? Cheers, L.
99
by: Shi Mu | last post by:
Got confused by the following code: >>> a >>> b >>> c {1: , ], 2: ]} >>> c.append(b.sort()) >>> c {1: , ], 2: , None]}
0
by: Fuzzyman | last post by:
It's finally happened, `Movable Python <http://www.voidspace.org.uk/python/movpy/>`_ is finally released. Versions for Python 2.3 & 2.4 are available from `The Movable Python Shop...
0
by: Kurt B. Kaiser | last post by:
Patch / Bug Summary ___________________ Patches : 398 open ( +5) / 3334 closed (+19) / 3732 total (+24) Bugs : 904 open ( -4) / 6011 closed (+36) / 6915 total (+32) RFE : 222 open...
206
by: WaterWalk | last post by:
I've just read an article "Building Robust System" by Gerald Jay Sussman. The article is here: http://swiss.csail.mit.edu/classes/symbolic/spring07/readings/robust-systems.pdf In it there is a...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.