473,785 Members | 2,283 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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
63 5180
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_mod ule_names
if 'msvcrt' in bims:
# Windows
from msvcrt import getch
elif 'termios' in bims:
# Unix
import tty, termios
def getch():
fd = sys.stdin.filen o()
old_settings = termios.tcgetat tr(fd)
try:
tty.setraw(sys. stdin.fileno())
ch = sys.stdin.read( 1)
finally:
termios.tcsetat tr(fd, termios.TCSADRA IN, old_settings)
return ch
else:
raise NotImplementedE rror, '... fill in Mac Carbon code here'


"Davor" <da*****@gmail. com> schrieb im Newsbeitrag
news:11******** *************@c 13g2000cwb.goog legroups.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.filen o()
old_settings = termios.tcgetat tr(fd)
try:
tty.setraw(sys. stdin.fileno())
ch = sys.stdin.read( 1)
finally:
termios.tcsetat tr(fd, termios.TCSADRA IN, 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.star tswith('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*********@zo ran.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,'H ello 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__.k eys():
ps += '%s: %s\n' % (e, str(self.__dict __[e]))
return ps

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

class invoice(printab le):
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 'cGV0ZXIubWFhc0 BtcGx1c3IuZGU=\ n'.decode('base 64')
-------------------------------------------------------------------
Jul 18 '05 #27

"Davor" <da*****@gmail. com> wrote in message
news:ct******** **@rumours.uwat erloo.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&simpl e" 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,'H ello 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***@somewher e.com> wrote in message
news:ct******** **@swifty.weste nd.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,'H ello
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

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

Similar topics

10
3692
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. Andrew dalke@dalkescientific.com
68
5897
by: Lad | last post by:
Is anyone capable of providing Python advantages over PHP if there are any? Cheers, L.
99
4678
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
1571
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 <http://voidspace.tradebit.com/groups.php>`_. The cost is £5 per distribution, payment by PayPal. £1 from every distribution goes to support the development of `SPE <http://pythonide.stani.be/>`_, the Python IDE.
0
325
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 ( -1) / 231 closed ( +2) / 453 total ( +1) New / Reopened Patches ______________________
206
8374
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 footprint which says: "Indeed, one often hears arguments against building exibility into an engineered sys- tem. For example, in the philosophy of the computer language Python it is claimed: \There should be one|and preferably only one|obvious...
0
9646
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9483
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10346
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10157
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10096
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9956
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8982
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5386
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5514
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.