python without OO

F

Fuzzyman

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
 
P

Premshree Pillai

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. :)
 
C

Claudio Grondi

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
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 said:
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()
 
N

Neil Benn

Davor said:
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
 
P

Peter Maas

Davor said:
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.
 
F

Frank Bechmann (w)

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

Thomas Bartkus

Davor said:
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
 
B

beliavsky

Peter said:
Davor said:
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,ages,sexes

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 ..."
 
T

Terry Reedy

Peter Maas said:
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
 
F

Francis Girard

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
 
P

PA

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
 
F

Francis Girard

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

Francis Girard
FRANCE
 
F

Frans Englich

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
 
M

Marc 'BlackJack' Rintsch

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
 
B

beliavsky

Nick said:
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.
 
D

Davor

Timo said:
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!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,149
Latest member
Vinay Kumar Nevatia0
Top