473,725 Members | 2,180 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Thoughts about Python

Hi

I don't have to talk about the beauty of Python and its clear and
readable syntax... but there are a few things that striked me while
learning Python.

I have collected those thoughts. I am sure there are many discussions
on the "problems" mentioned here. But I had this thoughts without
looking into any forums or anything... it is kind of feedback.

Thanks for this marvellous language,
Marco

*** Problem: clumsy static class methods

In order to create a static method we have to use a the builtin
staticmethod(fu nction):

class C (object):
def f(arg1, arg2, ...): ...
f = staticmethod(f)

Why? The speciality of a "static" method is: It has no access to any
instance vars. The following class is easier to read and understand
what a static method is about... as a positive side-effect: self is
not available and it can't be used!

class c (object):
def staticMethod(ar g1, arg2, ...):
# self is not handed in... hence I can't use the instance vars
pass
def normalMethod(se lf, arg1, arg2, ...):
pass

There is no need for the builtin... as I understand it: the builtin is
a workaround...

*** Problem: clumsy properties for classes

property( [fget[, fset[, fdel[, doc]]]])

class C(object):
def getx(self): return self.__x
def setx(self, value): self.__x = value
def delx(self): del self.__x
x = property(getx, setx, delx, "I'm the 'x' property.")
I don't like this one either. It is not necessary because it describes
something that should be clear by looking at the class/code. A
convention would make the syntax clearer and more intuitive and by
looking at the definition of a method you would know: This is a
getter, setter or deleter. My proposal:

all getters start with __get__
all setters start with __set__
all deleters start with __del__

If someone uses:

prop.x = 5

Python checks whether the var 'x' exists on prop. If it does - it is
set. If it doesn't exist Python checks for '__set__x' if it doesn't
exist either... a AttributeError is raised:
class PropertyExample (object):
"""A demonstration class for the property idea.

This class is used afterwards as follows:
prop = PropertyExample ()
prop.x = 5 # __set__x(self, 5) is called behind the scenes
print prop.x # __get__x(self) is called behind the scenes
del prop.x # __del__x(self) is called behind the scenes"""

def __init__(self):
self.__x = None

def __del__x(self):
del self.__x
def __get__x(self):
return self.__x
def __set__x(self, value):
self.__x = value

*** Problem: Many builtins are not necessary

Many builtins are not necessary. To name a few: min / max / len

This functions should be defined on the class:

["I", "like", "Python"].len()
"I".len()
{1:"I", "2":"like", 3:"Python"}.len ()
(1,2,3,4).len()

"Throwing away" this builtins would flatten the alreay flat learning
curve once more (you don't have to learn that many builtins) ... these
functions belong to the class and they are naturally expected there.
One weakness of a language as (Visual)Basic, PHP, ... is its payload
of available functions... Python's OO helps here to diminish the need
for lots of functions.
*** Problem: tuples are not necessary

Throw them away in the long run - for now make them depracted. It is
hard to argue in favour of tuples. There might to 2 reason:

1. It is MUCH faster than a list
2. We can't live without an immutable list

Cons:

1. I don't think that tuples deliver a big performance gain.
2. Python makes so many "soft" conventions (eg.: don't use
vars/methods with 2 leading underscores) but when it comes to tuples
the immutable issue is very important... why? I hope the tuples will
disappear in P3K.
*** Problem: builtins list() dict() ...

A list, a dictionary, a str, an int, a float are builtin functions...

myList = list()
myDict = dict()
myString = str(45)

The list-function instantiates a new list... it is actually nothing
but an overloaded List class. Why are the handed in as functions? In a
OO environment it should be more the instatiation of a class rather
than a function and classes start with an uppercase letter:

myList = List()
myDict = Dict()
myString = String(45)
Jul 18 '05 #1
39 3167
PP**********@sp ammotel.com (Marco Aschwanden) writes:
Hi

I don't have to talk about the beauty of Python and its clear and
readable syntax... but there are a few things that striked me while
learning Python.

I have collected those thoughts. I am sure there are many discussions
on the "problems" mentioned here. But I had this thoughts without
looking into any forums or anything... it is kind of feedback.

Thanks for this marvellous language,
Marco

*** Problem: clumsy static class methods

In order to create a static method we have to use a the builtin
staticmethod(fu nction):

class C (object):
def f(arg1, arg2, ...): ...
f = staticmethod(f)
See PEP 318 (and current discussion on python-dev).
Why? The speciality of a "static" method is: It has no access to any
instance vars. The following class is easier to read and understand
what a static method is about... as a positive side-effect: self is
not available and it can't be used!

class c (object):
def staticMethod(ar g1, arg2, ...):
# self is not handed in... hence I can't use the instance vars
pass
def normalMethod(se lf, arg1, arg2, ...):
pass

There is no need for the builtin... as I understand it: the builtin is
a workaround...
What's so special about self? I really don't like the idea of
argument names keying this kind of change in behaviour.
*** Problem: clumsy properties for classes

property( [fget[, fset[, fdel[, doc]]]])

class C(object):
def getx(self): return self.__x
def setx(self, value): self.__x = value
def delx(self): del self.__x
x = property(getx, setx, delx, "I'm the 'x' property.")
I don't like this one either. It is not necessary because it describes
something that should be clear by looking at the class/code. A
convention would make the syntax clearer and more intuitive and by
looking at the definition of a method you would know: This is a
getter, setter or deleter. My proposal:

all getters start with __get__
all setters start with __set__
all deleters start with __del__

If someone uses:

prop.x = 5

Python checks whether the var 'x' exists on prop. If it does - it is
set. If it doesn't exist Python checks for '__set__x' if it doesn't
exist either... a AttributeError is raised:
class PropertyExample (object):
"""A demonstration class for the property idea.

This class is used afterwards as follows:
prop = PropertyExample ()
prop.x = 5 # __set__x(self, 5) is called behind the scenes
print prop.x # __get__x(self) is called behind the scenes
del prop.x # __del__x(self) is called behind the scenes"""

def __init__(self):
self.__x = None

def __del__x(self):
del self.__x
def __get__x(self):
return self.__x
def __set__x(self, value):
self.__x = value
You seem really fond of magic names...

By the way, Python 2.2 introduced the capacity for staticmethods and
properties and consciously decided not to add syntax for the same
until there was some experience in using these things. So it's known
that there is some discomfort here, but it's not yet clear (to me, at
least) what a good syntax *is*. I hope you're not too offended if I
say that your suggestion doesn't seem instantly wonderful.
*** Problem: Many builtins are not necessary
Pah. So what? If you want minimailty scheme is over there ====>
Many builtins are not necessary. To name a few: min / max / len

This functions should be defined on the class:
Says you!

[...]
*** Problem: tuples are not necessary
Says you! Here's a hint: hash([]).

[...] *** Problem: builtins list() dict() ...

A list, a dictionary, a str, an int, a float are builtin functions...

myList = list()
myDict = dict()
myString = str(45)


Pedantry: no they're not, they're builtin types.

I think you might be expecting something other of Python than what it
is. Nothing you suggest is completely ridiculous, just, well,
slightly un-Pythonic. I suggest you continue using Python for a few
more weeks and read your list again.

Cheers,
mwh

--
MARVIN: Oh dear, I think you'll find reality's on the blink again.
-- The Hitch-Hikers Guide to the Galaxy, Episode 12
Jul 18 '05 #2
PP**********@sp ammotel.com (Marco Aschwanden) wrote in
news:15******** *************** ***@posting.goo gle.com:
I have collected those thoughts. I am sure there are many discussions
on the "problems" mentioned here. But I had this thoughts without
looking into any forums or anything... it is kind of feedback.
I think you should spend a bit of time reading the PEPs and the python-dev
mailing list archives. A lot of what you say has been discussed previously,
and it would be good if you could take the earlier discussion on board and
then see where your thoughts lead you.

*** Problem: clumsy static class methods
This has been widely discussed elsewhere and various solutions have been
proposed.

*** Problem: clumsy properties for classes
As for static methods various ways to improve this have been suggested. You
should read the discussions on python-dev to see the various viewpoints.

*** Problem: Many builtins are not necessary

Many builtins are not necessary. To name a few: min / max / len

This functions should be defined on the class:

["I", "like", "Python"].len()
"I".len()
{1:"I", "2":"like", 3:"Python"}.len ()
(1,2,3,4).len()
The advantage of min and max as builtins are that they work on any
sequence. In particular they work on iterators. Having functions that apply
to an arbitrary sequence avoids a lot of potential code duplication.
"Throwing away" this builtins would flatten the alreay flat learning
curve once more (you don't have to learn that many builtins) ... these
functions belong to the class and they are naturally expected there.
One weakness of a language as (Visual)Basic, PHP, ... is its payload
of available functions... Python's OO helps here to diminish the need
for lots of functions.
There are other builtins I would throw away first. Note that you can't
actually throw any of these builtins away: one of Pythons great strengths
are the lengths it goes to to maintain backward compatibility. Some of the
less useful builtins are being relegated to backwaters of the
documentation, but they will remain as builtins for the foreseeable future.


*** Problem: tuples are not necessary

Throw them away in the long run - for now make them depracted. It is
hard to argue in favour of tuples. There might to 2 reason:

1. It is MUCH faster than a list
2. We can't live without an immutable list
Forget the speed and memory difference. The main argument for tuples as a
separate type are to use as dictionary keys. How do you propose to handle
dictionary keys without tuples?

*** Problem: builtins list() dict() ...

A list, a dictionary, a str, an int, a float are builtin functions...
No they aren't. They are types, not functions.

myList = list()
myDict = dict()
myString = str(45)

The list-function instantiates a new list... it is actually nothing
but an overloaded List class. Why are the handed in as functions? In a
OO environment it should be more the instatiation of a class rather
than a function and classes start with an uppercase letter:

myList = List()
myDict = Dict()
myString = String(45)


So they don't follow your naming convention. If this is a big problem for
you, then add some new globals in your own programs. The type 'file' is
already aliased as 'open'. You can't remove the existing builtins (since
that would break the library), but there is nothing to stop you adding your
own either in the __builtin__ module, or as a separate module containing
your aliases.

FWIW, I agree that the builtins that exist aren't the best choice for type
names --- too often they collide with the 'obvious' variable names that
python newcomers choose and then they wonder why their call to 'str' blow
up when they used a variable 'str' a few lines earlier.
Jul 18 '05 #3
Duncan Booth <me@privacy.net > writes:
PP**********@sp ammotel.com (Marco Aschwanden) wrote in
news:15******** *************** ***@posting.goo gle.com:
*** Problem: Many builtins are not necessary

Many builtins are not necessary. To name a few: min / max / len

This functions should be defined on the class:

["I", "like", "Python"].len()
"I".len()
{1:"I", "2":"like", 3:"Python"}.len ()
(1,2,3,4).len()


The advantage of min and max as builtins are that they work on any
sequence. In particular they work on iterators. Having functions that apply
to an arbitrary sequence avoids a lot of potential code duplication.


Do you mean code duplication on the user side? Or code duplication in
Python's implementations ? In the latter case, it seems strange to
force inconsistent method/function usage on thousands of developers
just in order to save a couple of lines in Python's source code.

To me, Python's builtins are by far not a "problem", but I admit that
I never understood why astring.len() doesn't work.
Jul 18 '05 #4
Matthias <no@spam.pls> wrote in
news:36******** *****@goya03.ti .uni-mannheim.de:
The advantage of min and max as builtins are that they work on any
sequence. In particular they work on iterators. Having functions that
apply to an arbitrary sequence avoids a lot of potential code
duplication.
Do you mean code duplication on the user side? Or code duplication in
Python's implementations ? In the latter case, it seems strange to
force inconsistent method/function usage on thousands of developers
just in order to save a couple of lines in Python's source code.


I mean code duplication on the user side. A function that operates on every
iterator or sequence type is far more useful than a protocol that more
often than not wouldn't be implemented.

To me, Python's builtins are by far not a "problem", but I admit that
I never understood why astring.len() doesn't work.

Because it would have to begin and end with two underscores (thats the
naming convention for special methods), and astring.__len__ () already does
what you want. But I think it is mostly for historical reasons.
Jul 18 '05 #5
In article <15************ **************@ posting.google. com>,
Marco Aschwanden <PP**********@s pammotel.com> wrote:

*** Problem: Many builtins are not necessary

Many builtins are not necessary. To name a few: min / max / len

This functions should be defined on the class:

["I", "like", "Python"].len()
"I".len()
{1:"I", "2":"like", 3:"Python"}.len ()
(1,2,3,4).len( )

"Throwing away" this builtins would flatten the alreay flat learning
curve once more (you don't have to learn that many builtins) ... these
functions belong to the class and they are naturally expected there.
One weakness of a language as (Visual)Basic, PHP, ... is its payload
of available functions... Python's OO helps here to diminish the need
for lots of functions.


"Practicali ty beats purity"; if you're not familiar with that, start up
an interactive Python session and type "import this".

In this case, this means that Guido thinks that len() is such a common
usage that it works better as a function than a method.
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

"Do not taunt happy fun for loops. Do not change lists you are looping over."
--Remco Gerlich, comp.lang.pytho n
Jul 18 '05 #6

"Marco Aschwanden" <PP**********@s pammotel.com> wrote in message
news:15******** *************** ***@posting.goo gle.com...
I have collected those thoughts. I am sure there are many discussions
on the "problems" mentioned here.
Yes, there have been. Do read some if you are really interested.
*** Problem: clumsy properties for classes
The problem is currently under discussion. Your fix is based on thinking
'self' to be a keyword, which it is not, instead of a usage convention for
English language programmers. Python is not <language x>.
class c (object):
def staticMethod(ar g1, arg2, ...): pass
# self is not handed in... hence I can't use the instance vars
Yes it is and yes you can if this method called on an instance. You have
simply called the instance 'arg1' instead of 'self'.
def normalMethod(se lf, arg1, arg2, ...):
pass
If you follow this by normalMethod = staticmethod(no rmalMethod), then
'self' is *not* an instance.
Static methods are very rare. You left out a proposal for the more common
and more useful classmethod.

.... Many builtins are not necessary.
Many people agree.
To name a few: min / max / len
But people wildly disagree on which should be axed.
This functions should be defined on the class:
This syntax uniformatizing suggestion comes up about once a year. It
overlooks the fact that uniformity is lost as soon as a user writes a
sequence function (for instance, variance()). I know, we could abolish
functions and only have methods. But if you want that, choose a different
language.

Even more, It also overlooks the tremendous advantages of generic
programming with Python. If I write an iterable type, it can be used with
any sequence function, current or future. Conversely, if I write a
sequence (iterable) function, it can be used with any iterable object,
current or future -- without subclassing or access to source code. Your
proposed handcuff of requiring a specifc method for each type - function
combinatin leads to an M*N explosion of code and coding work.

Quiz: how would you rewrite map(len, ['abc', (1,2,3,4), [5,6]]) if len()
were a method?
classes start with an uppercase letter:
myList = List()


This appears to be a convention or rule you learned from another language.
Though some Python programmers follow it, tt is not part of Python.

Terry J. Reedy


Jul 18 '05 #7

"Matthias" <no@spam.pls> wrote in message
news:36******** *****@goya03.ti .uni-mannheim.de...
Duncan Booth <me@privacy.net > writes:
The advantage of min and max as builtins are that they work on any
sequence. In particular they work on iterators. Having functions that apply to an arbitrary sequence avoids a lot of potential code duplication.
Do you mean code duplication on the user side? Or code duplication in
Python's implementations ?


Python's generic programming saves user code.

Write a function taking an iterable argument and it can be used with any of
the countable infinity of possible iterable types, current and future. For
free, without having to subclass or otherwise attach the function as a
method to each.

Write an iterable type and it can be fed to any of the countable infinity
of possible sequence functions, written and yet to be written. For free,
without adding them all as methods, which is impossible anyway for future
functions.
In the latter case,
But it is both cases, so your consequent does not follow.
To me, Python's builtins are by far not a "problem", but I admit that
I never understood why astring.len() doesn't work.


Because there is currently no process to make generic functions accessible
(aliased) as specific methods. Possible (but not-serious) proposal: Add
interface objects with attribute __takes__ being a set of functions which
takes objects implementing that interface as a single argument. Give types
a set of interfaces called __implements__. If attribute look-up fails,
search __takes__ for interfaces in __implements__. But you now you have
to explicitly register objects with the sets, and you still have problems
with interfaces (virtual types) often being too narrow, too broad, and/or
too numerous and what to do with multiparameter functions. Isn't
len(astring) easier, as well as one char shorter?

Terry J. Reedy


Jul 18 '05 #8
Duncan Booth wrote:
The advantage of min and max as builtins are that they work on any
sequence. In particular they work on iterators. Having functions
that apply to an arbitrary sequence avoids a lot of potential code
duplication.


Wouldn't subclassing be an appropriate solution? The most general
sequence class/type could define a len method and the others would
inherit it and override it if they have different length semantics. In
fact, Python already does this with the __len__ magic method. Having a
builtin function whose implementation is defined with a magically named
method seems an awkward design. Why not have just the method and do
away with the function?

--
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead. Go, instead, where there is
no path, and leave a trail."
--author unknown
Jul 18 '05 #9
Terry Reedy wrote:
Quiz: how would you rewrite map(len, ['abc', (1,2,3,4), [5,6]]) if
len() were a method?


[ a.len() for a in ['abc', (1,2,3,4), [5,6]] ]

--
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead. Go, instead, where there is
no path, and leave a trail."
--author unknown
Jul 18 '05 #10

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

Similar topics

30
2148
by: Stephen Horne | last post by:
Some more looping thoughts - this time on integer for loops... There may be some hint towards PEP284 (integer for loops) in a review of ideas from other languages, but I'm damned if i can figure it out. I spent some time thinking about it and couldn't find anything that would cover the issue. All I came up with was the recognition that some other languages have 'for' and 'foreach' loops. But Python went down the route of using 'for'...
8
1427
by: Edward K. Ream | last post by:
The documentation for encoding lines at C:\Python23\Doc\Python-Docs-2.3.1\whatsnew\section-encodings.html states: "Encodings are declared by including a specially formatted comment in the first or second line of the source file." In fact, contrary to the implication, the Python 2.3 parser does not look
5
1655
by: b-blochl | last post by:
I wonder about the huge traffic in the question how many tuples are dispensible. I find that a question of only ternary or quarterny order - use it or use it not (free after Shakespears "to be or not to be). Well, I had my part on that. But introducing students to python as a first programming language lists and tuples are astoninglishy always constant points of confusion as well as the other points of the citatet list. I will not...
1
1469
by: asdf sdf | last post by:
i need some advice. i'm a back end programmer historically, but have been exploring python for webapps and enjoying it. i need to build some simple Win client-server or standalone apps. the result needs to look professional and attractive, and i need something i can get working fairly quickly with a modest learning curve. i'm looking at wxPython, because that is a pythonic solution. but i'm concerned about the scarcity of gentle...
1
1519
by: Chris | last post by:
I was first exposed to Python in '94-95 by a fellow comp sci student. After a brief "play time" I discarded it was too radical. I *hated* the indentation == block of code theme. Besides, Forth was the One True Language(tm). :) Fast forward 6-7 years of real world programming in VB, C, NATURAL (a COBAL derived quasi 4GL), PHP, Perl and others. Programming wan't my main job, but I did it a bunch. Never wrote anything beyond toys in...
4
1406
by: John Benson | last post by:
Hi, I've been reading the above-titled book and it looks like some major Python and Zope features have been cherry-picked for pushing down into .NET, like application memory management (Python interpreter), and prefabricated website user management (Zope). I know that these didn't originate with Python and Zope, and also that .NET adds extra Microsoft-specific goodies. However, the real possibility is that the Microsoft-centricity of...
24
1984
by: Dave Benjamin | last post by:
Guido gave a good, long interview, available at IT Conversations, as was recently announced by Dr. Dobb's Python-URL! The audio clips are available here: http://www.itconversations.com/shows/detail545.html http://www.itconversations.com/shows/detail559.html I'd like to comment on a few parts of that interview. One thing Guido mentions in his comparison of ABC (Python's predecessor) and
18
1837
by: spiffo | last post by:
The Main Issue in a nutshell I am a corporate developer, working for a single company. Got a new project coming up and wondering if I should stay with Python for this new, fairly large project, are jump back on the 'safe' M$ bandwagon using a dot net language? Cross platform is NOT an issue, but COMPLETE control/compatability with MsSql Server (current and future versions) certainly is. Quick History
1
5465
by: James T. Dennis | last post by:
I've been thinking about the Python mmap module quite a bit during the last couple of days. Sadly most of it has just been thinking ... and reading pages from Google searches ... and very little of it as been coding. Mostly it's just academic curiosity (I might be teaching an "overview of programming" class in a few months, and I'd use Python for most of the practical examples to cover a broad range of programming topics, including the...
0
8888
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
9401
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...
1
9176
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
9113
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
8097
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
6011
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4519
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
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2157
bsmnconsultancy
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.