python without OO | Bytes (2024)

Davor

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

Subscribe Reply

63 python without OO | Bytes (1) 5104 python without OO | Bytes (2)

  • <
  • 1
  • 2
  • 3
  • 4
  • 5
  • >
  • Last »

Alex Martelli

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

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

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, getanother character, etc. If I just use stdin.read(1), it waits until I finishtyping 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

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

Premshree Pillai

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

Miki Tebeka

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

Neil Benn

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

Peter Maas

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

Thomas Bartkus

"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 Pythonat all. It seems you could be happy doing BASH scripts for Linux or DOSbatch 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

beliavsky

Peter Maas wrote:

Davor schrieb:
so initially I was hoping this is all what Python is about, butwhen I started looking into it it has a huge amount of additional (mainlyOO) 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 usingPython. 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

Terry Reedy

"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

  • <
  • 1
  • 2
  • 3
  • 4
  • 5
  • >
  • Last »

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

Similar topics

10 3670

author index for Python Cookbook 2?

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

Python

68 5805

Python or PHP?

by: Lad |last post by:

Is anyone capable of providing Python advantages over PHP if there are any? Cheers, L.

Python

99 4602

about sort and dictionary

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]}

Python

1548

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

Python

325

Weekly Python Patch/Bug Summary

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 ______________________

Python

206 8222

Python's "only one way to do it" philosophy isn't good?

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

Python

7694

What is ONU?

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

General

7921

Problem With Comparison Operator <=> in G++

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

C / C++

7964

Discussion: How does Zigbee compare with other wireless protocols in smart home applications?

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

General

6278

AI Job Threat for Devs

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

Career Advice

1 5504

Access Europe - Using VBA to create a class based on a table - Wed 1 May

by: isladogs |last post by:

The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...

Microsoft Access / VBA

5217

Couldn’t get equations in html when convert word .docx file to html file in C#.

by: conductexam |last post by:

I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...

C# / C Sharp

3636

Windows Forms - .Net 8.0

by: adsilva |last post by:

A Windows Forms form does not have the event Unload, like VB6. What one acts like?

Visual Basic .NET

1 1208

How to add payments to a PHP MySQL app.

by: muto222 |last post by:

How can i add a mobile payment intergratation into php mysql website.

PHP

936

Comprehensive Guide to Website Development in Toronto: Expert Insights from BSMN Consultancy

by: bsmnconsultancy |last post by:

In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

General

python without OO | Bytes (2024)

References

Top Articles
Latest Posts
Article information

Author: Sen. Ignacio Ratke

Last Updated:

Views: 5831

Rating: 4.6 / 5 (56 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Sen. Ignacio Ratke

Birthday: 1999-05-27

Address: Apt. 171 8116 Bailey Via, Roberthaven, GA 58289

Phone: +2585395768220

Job: Lead Liaison

Hobby: Lockpicking, LARPing, Lego building, Lapidary, Macrame, Book restoration, Bodybuilding

Introduction: My name is Sen. Ignacio Ratke, I am a adventurous, zealous, outstanding, agreeable, precious, excited, gifted person who loves writing and wants to share my knowledge and understanding with you.