I'm a python addict !

L

Linuxguy123

I just started using python last week and I'm addicted.

I hate Perl. I never did learn to use it with any competence. I has to
be the most obfuscated, cryptic language I've ever seen. Making it
"object oriented" only makes it worse !

While I am at it, I dislike bash shell programming too.

Man, I love Python ! Its so clean and easy to use. Its so complete.
It links into everything one way or another... Java, C, C++, Qt, KDE,
SWT, Swing and probably more things that I don't know about. Python
makes sense. Python is readable.

I will never write another Perl or Bash script again. I will never use
another low level language to do simple things again.

I love how Python has object member lists in PyDev in Eclipe. It makes
it easy to use and explore the language and objects.

I wrote a simple command line serial emulator in about 10 minutes using
the PySerial library. Unbelievable.

I see a lot of Python in my future.
 
P

Paul McGuire

I just started using python last week and I'm addicted.
<snip youthful exuberance>
I see a lot of Python in my future.

Bravo, welcome, and well-said!

Your sentiments mirror and resonate with those of many on this list.
About 6 years ago I wanted a scripting language to work with,
*anything* but more Tcl/Tk! Python the language had many features and
language design decisions that just "felt right," and the natural feel
of the object model allowed me to leverage much of the OO theory I had
learned using Java and C++.

And THEN, it began to dawn on me that a lot of that theory is actually
crutch, bailing-wire, and gum, put there to work around the static
typing rigidity of C++, Java and their ilk. As much as I loved Scott
Meyers' "Effective C++" books, many of their idioms and tricks just
fall away as unnecessary in Python. Interfaces? Python don't need no
steenking interfaces! The interface concept is still useful for
organizing your thinking and OO design, but the implementation is far
freer, as you find that an object's conformance to an interface is
only determined/required at runtime, not at some long-distant compile
step in a library nested N levels deep in your hierarchy.

Python exposes many of its dynamic hooks through magic __xxx__
methods. Need to write a proxy wrapper around an object of type X to
supercede method Y, but you don't want to write all thouse tedious
passthru methods for the X class's methods A thru R? Just implement
your special method Y, and let a __getattr__ method pass all the other
calls on to the underlying object. Instant Proxy!

Want to change the type/behavior of an object from class A to class
B? How about this:

aobj = A()
aobj.__class__ = B

Try *that* in as simple-looking C++ or Java!

Python's learning curve can be gentle or steep, depending on your own
inclination. My advice? Push yourself up as quickly as you can.
Quickly put aside this kind of code:

for i in range(len(datalist)):
# do something with datalist

and start thinking in iterators:

for item in datalist:
# do something with item

Need to read through a text file?

for line in file("xyzzy.dat"):
# do something with each line

Master the clean look and feel of a list comprehension or generator
expression, over explicit for loops. Need to build a list of the odd
numbers up to 100? Instead of this:

oddnums = []
for n in range(100):
if n % 2:
oddnums.append(n)

learn to do this:

oddnums = [ n for n in range(100) if n % 2 ]

Learn the native data structures - tuple, list, dict, set. Learn the
dict idiom that serves as Pythons version of a switch statement.
Check out the itertools module, a cunning mix of elegance and
wizardry. The standard lib is a trove of well-oiled and production-
tested code, but the community is not shy about producing additional
modules, many with liberal licensing - image processing, text
processing/parsing, discrete-event simulation, optimization, genetic
algorithms, web/network apps and IPC, ... Google and ye shall find.

Write a generator method to yield a sequence of useful values (odd
numbers, primes, consonants, fibonacci's, whatever). You can
certainly write a lot of Python without ever using these intermediate/
advanced features, but one day you'll give it a shot and think "Dang!
what was the big deal? I wish I'd tried this sooner!"

Yet having said that, in 6 years I've not yet tried to write a C
extension for Python. But I'm told that this too is a well-blazed
trail if you feel the need.

Dig in! And post back here if you get stuck. Be confident that Python
has been employed in a wide range of applications and application
domains, and that if a particular feature seems to be missing, it may
be because Python takes a slightly different angle on the problem.

Ah, those heady days of youth, when the world was fresh, and the
idioms of Python were still new and ripe to discover!

I envy you, Linuxguy123, I envy you...

Enjoy!
-- Paul
 
A

Aahz

I just started using python last week and I'm addicted.

Welcome! Just be aware that excessive Perl-bashing is considered
somewhat tasteless on this newsgroup, but the occasional snide comment
should be fine. ;-)
 
R

Russ P.

I will never write another Perl or Bash script again.

I still use bash for orchestrating the execution of a series of other
scripts and/or programs (including python programs). I know you can do
that in python, but I find bash simpler to use for that purpose. Then
again, that may be just because I learned bash before I learned python.
 
R

Robert Kern

Welcome! Just be aware that excessive Perl-bashing is considered
somewhat tasteless on this newsgroup, but the occasional snide comment
should be fine. ;-)

Or bash-bashing for that matter. :)

but-zsh-really-is-better'ly yrs,

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
 
R

Russ P.

Or bash-bashing for that matter.  :)

but-zsh-really-is-better'ly yrs,

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco

Come to think of it, when I use bash to run a series of python
scripts, I could call it "bashing Python."
 
P

Paul McGuire

Wow.  That looks very powerful and fun.  But scary.  Any thoughts on how
you would use that in a way that wouldn't unleash sulphurous code
smells?

This technique is perfect for implementing the GoF State pattern.

In the State pattern, you implement behavior for an object's various
states using one of several interchangeable classes. The classes are
"interchangeable" in that they all implement a common interface. Here
is my favorite State pattern example, a traffic light:


import time

class TrafficLight(object):
pass

class RedLight(TrafficLight):
cars_can_go = False
pedestrians_can_cross = True
color = (255,0,0)
duration = 20

class YellowLight(TrafficLight):
cars_can_go = True
pedestrians_can_cross = False
color = (255,255,0)
duration = 5

class GreenLight(TrafficLight):
cars_can_go = True
pedestrians_can_cross = False
color = (0,255,0)
duration = 15

# now add in next_state class vars for state transitions
RedLight.next_state = GreenLight
YellowLight.next_state = RedLight
GreenLight.next_state = YellowLight
TrafficLight.initial_state = RedLight

# run a traffic light for a while...
can_they = lambda cond : ("can't","can")[cond]
light = TrafficLight.initial_state()
while 1:
print light.__class__.__name__
print "waiting for", light.duration, "seconds"
print "Cars", can_they(light.cars_can_go), "go"
print "People", can_they(light.pedestrians_can_cross), "cross"
print
time.sleep(light.duration)

# how you have to do it in C++ and Java
# light = light.next_state()

# using Python
light.__class__ = light.next_state


Gives this output:

RedLight
waiting for 20 seconds
Cars can't go
People can cross

GreenLight
waiting for 15 seconds
Cars can go
People can't cross

YellowLight
waiting for 5 seconds
Cars can't go
People can't cross

RedLight
waiting for 20 seconds
Cars can't go
People can cross

.... and so on ...



In Python, the base TrafficLight class isn't even necessary ("don't
need no stinking interfaces!"), although it is a good place to define
default behavior, and it helps tie together the other classes from a
self-documentation standpoint. But any class that has the necessary
attributes would suffice, whether it inherits from TrafficLight or
not.

class HoldForEmergencyVehiclesLight(object):
cars_can_go = False
pedestrians_can_cross = False
color = (255,0,0)


-- Paul
 
P

Paul McGuire

Thanks.  That makes sense.  But your example creates a new instance of
the new class each time, rather than changing the class of a persistent
instance, as the original example, to which I was responding, did.

Look closer. The line that creates a new instance is commented out,
with the notation "how you have to do it in C++ and Java". The actual
Python code is just below, and just assigns a new class to
self.__class__, as in the original example.

-- Paul
 
J

J Kenneth King

Linuxguy123 said:
I just started using python last week and I'm addicted.

I hate Perl. I never did learn to use it with any competence. I has to
be the most obfuscated, cryptic language I've ever seen. Making it
"object oriented" only makes it worse !
.. <snip> ..

I program full-time in Python, so I share your excitement and
enthusiasm. But bashing Perl like that doesn't make you sound very
smart. I'm probably one of the very few Python programmers who came from
(and still occassionally) use Perl. I've written non-trivial programs in
it and from my experience I can tell you that it's actually a great
language. The Moose object system is well beyond Python's class
system. But I guess you wouldn't know that.

So yay for Python, but don't get in the habit of criticising that which
you do not know.
 
J

J Kenneth King

J Kenneth King said:
I program full-time in Python, so I share your excitement and
enthusiasm. But bashing Perl like that doesn't make you sound very
smart. I'm probably one of the very few Python programmers who came from
(and still occassionally) use Perl. I've written non-trivial programs in
it and from my experience I can tell you that it's actually a great
language. The Moose object system is well beyond Python's class
system. But I guess you wouldn't know that.

So yay for Python, but don't get in the habit of criticising that which
you do not know.

I just realized this might become flame-bait. Please disregard the
flamey bits. :(
 
B

Bruno Desthuilliers

Paul McGuire a écrit :
This technique is perfect for implementing the GoF State pattern.

Except when it is not !-)

I tried twice to use this trick in "real life" code, and in both cases,
it ended up being much more complicated than implementing the state
pattern the canonical way. Not to say that it's hopeless - just that
there's the usual difference between theory and practice.
 
A

afriere

    # how you have to do it in C++ and Java
    # light = light.next_state()

    # using Python
    light.__class__ = light.next_state

I'm sure you can, but why poke yourself in the eye with a blunt
stick? ;)

IMO there are two obvious problems with the latter approach. Firstly
the information about the next state is left lying about in some
namespace separate from the object, whereas the object itself ought to
know what it's 'next_state' is (or, more correctly, how to determine
it).

Secondly you miss the opportunity of sending a signal to the new
state. Consider that in some jurisdictions the amber light shows
before the green as well as before the red (yeah, I know is that an
invitation for drag racing or what!?). If you called next_state as a
verb you could pass the current state as an argument and the amber (or
yellow, if you prefer) light could work which of the two possible next
states to call in turn. The fact that this behaviour is, in this
example, peculiar to the amber light, demonstrates the pertinence of
my first objection above.

Fortunately the "C++ and Java" approach, (though I would never want to
be seen advocating the C++ or Java approach to anything), is in this
case available in Python as well, at the cheaper price of fewer
characters and arguably greater readibility to boot.

I know, Iknow ... you wanted to show how that code could be used in a
non "sulphurous" way. Which just goes to show that the devil makes
work for idle hands ... or foils the best laid plans ... or is in the
detail ... or something sulphurous. :)
 

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,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top