473,769 Members | 4,202 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Re: Understanding the pythonic way: why a.x = 1 is better thana.setX(1) ?

Sorry... pressed enter but really didn't want to.

As I said, let's say I have a class

class A:
def __init__(self):
self.x = None

Python makes the decision to allow the developers to directly access
the attribute "x", so that they can directly write: "a.x = 1", or
whatever; this has for me the unfortunate side effect that if I write,
for example "a.y = 1", when I really wanted to write "a.x = 1" no one
cares about it, and I'm unable to spot this error until later.

Of course, I know that while I'm fresh, I've a good knowledge of the
code, and anything else, I will be able to avoid such stupid errors;
however, I'm afraid of the times when I'm tired, when I have to put my
hands on the code of someone else, and so on.

Please, understand that I'm not stating that python is wrong... after
all, if it is wrong, I can move to a language like Java, which has a
different approach on it. I'm really very interested in reading past
discussion on it, if they are available.

Regards
Marco

On Thu, Sep 4, 2008 at 12:57 PM, Marco Bizzarri
<ma************ @gmail.comwrote :
Let's say I've a class a, where I can write:

--
Marco Bizzarri
http://notenotturne.blogspot.com/
http://iliveinpisa.blogspot.com/


--
Marco Bizzarri
http://notenotturne.blogspot.com/
http://iliveinpisa.blogspot.com/
Sep 4 '08 #1
13 1178
Of course, I know that while I'm fresh, I've a good knowledge of the
code, and anything else, I will be able to avoid such stupid errors;
however, I'm afraid of the times when I'm tired, when I have to put my
hands on the code of someone else, and so on.

Please, understand that I'm not stating that python is wrong... after
all, if it is wrong, I can move to a language like Java, which has a
different approach on it. I'm really very interested in reading past
discussion on it, if they are available.
This has not much to do with the question of setters and getters. Because in
your code you could write

def setX(self, x):
self.y = x

def getX(self):
return self.x

So the error occurs in the same way.

What you are essentially asking is: why is python dynamic instead of static?

Because *that* is what is the difference. In a static language, you need to
declare first what you want to be available, e.g. which variables and
methods are available and such.

Of course then the compiler (or whoever evaluates the static declarations)
can puke on you if you attempt a stunt like the one you describe.

Python (and other languages such as Ruby, Javascript) chose other. They give
you the freedom to add instance variables (or even methods) at will, with
the cost of the occasional error like the above.

OTOH, Java makes me write soooo much more code that me becoming tired and
doing some stupid mistake (and there are lots of them doable in static
languages as well, otherwise no C/C++ or Java-program would crash....)
becomes much more likely....YMMV.

Diez
Sep 4 '08 #2
Marco Bizzarri a écrit :
Sorry... pressed enter but really didn't want to.

As I said, let's say I have a class

class A:
def __init__(self):
self.x = None

Python makes the decision to allow the developers to directly access
the attribute "x",
So do Java, if you make your attribute public (which would be a big
error given Java's lack of support for computed attribute, but this is
another problem).
so that they can directly write: "a.x = 1", or
whatever; this has for me the unfortunate side effect that if I write,
for example "a.y = 1", when I really wanted to write "a.x = 1" no one
cares about it,
I assume *you* do !-)

But this is barely related to having explicit setters or not - it comes
from the fact that the default[1] Python's object behaviour is to
support arbitrary attribute setting.

[1] some objects don't, but this is mostly for optimization reasons.
and I'm unable to spot this error until later.
Not sure, but IIRC tools like pylint or pychecker might be able to warn
you about this. But anyway :
Of course, I know that while I'm fresh, I've a good knowledge of the
code, and anything else, I will be able to avoid such stupid errors;
however, I'm afraid of the times when I'm tired, when I have to put my
hands on the code of someone else, and so on.
The edit/test cycle in Python is usually fast enough so you should spot
the problem *pretty* quickly. This is at least what I learned from 8+
years of python (and a couple other dynamic languages) programming...

Not to say that problems like the one you mention (or similar problems
with dynamic typing etc) never happens, nor that they're never painful
to track down and fix - just that they happen way less often than one
might fear, and are most of the time really quickly spotted and fixed.
Please, understand that I'm not stating that python is wrong... after
all, if it is wrong, I can move to a language like Java, which has a
different approach on it.
I don't think it's a matter of "right" or "wrong" - mostly a matter of
tradeoffs and balance. But if you go for static typing and (allegedly)
provable correctness, you may want to have a look at languages like OCaml.
I'm really very interested in reading past
discussion on it, if they are available.
Well... Most of these "discussion s" alas boil down to bondage&discipl ine
proponants asserting - against all evidences - that dynamic languages
are unsafe and unusable for anything else than simple throw-away scripts
or toy projects, and dynamic proponants arguing - against all evidences
- that static typing and everything related is just a waste of time
(FWIW, you might find myself in the first camp until approx year 2k and
the second for the five or six following years). And sometimes, someone
a bit more sensible trying to take a more balanced approach to the
problem, usually to no avail.
Sep 4 '08 #3
On Thu, Sep 4, 2008 at 1:19 PM, Diez B. Roggisch <de***@nospam.w eb.dewrote:
>
What you are essentially asking is: why is python dynamic instead of static?
Most probably you're right. Maybe I will make a trip back to my
university books and take a look at them again :-)

Thanks
Marco

--
Marco Bizzarri
http://notenotturne.blogspot.com/
http://iliveinpisa.blogspot.com/
Sep 4 '08 #4
On Thu, Sep 4, 2008 at 4:39 PM, Marco Bizzarri <ma************ @gmail.comwrote :
>
Most probably you're right. Maybe I will make a trip back to my
university books and take a look at them again :-)
Meant: you *are* right. Sorry.

Saluti
Marco

--
Marco Bizzarri
http://notenotturne.blogspot.com/
http://iliveinpisa.blogspot.com/
Sep 4 '08 #5
On Sep 4, 7:09*am, "Marco Bizzarri" <marco.bizza... @gmail.comwrote :
Sorry... pressed enter but really didn't want to.

As I said, let's say I have a class

class A:
* * def __init__(self):
* * * * *self.x = None

Python makes the decision to allow the developers to directly access
the attribute "x", *so that they can directly write: "a.x = 1", or
whatever; this has for me the unfortunate side effect that if I write,
for example "a.y = 1", when I really wanted to write "a.x = 1" no one
cares about it, and I'm unable to spot this error until later.

Of course, I know that while I'm fresh, I've a good knowledge of the
code, and anything else, I will be able to avoid such stupid errors;
however, I'm afraid of the times when I'm tired, when I have to put my
hands on the code of someone else, and so on.
So what happens in Java (or any language for that matter) if there are
indeed two attributes x and y with the same type and you mistype the
one for the other ? Or if you meant to write x-y instead of y-x ?

When coding tired or on someone's else code, stupid errors are the
ones you should worry the least about.

George
Sep 4 '08 #6
On Sep 4, 7:09 am, "Marco Bizzarri" <marco.bizza... @gmail.comwrote :
Sorry... pressed enter but really didn't want to.

As I said, let's say I have a class

class A:
def __init__(self):
self.x = None

Python makes the decision to allow the developers to directly access
the attribute "x", so that they can directly write: "a.x = 1", or
whatever; this has for me the unfortunate side effect that if I write,
for example "a.y = 1", when I really wanted to write "a.x = 1" no one
cares about it, and I'm unable to spot this error until later.

You can write code to guard against this if you want:

class A:
legal = set(["x"])
def __setattr__(sel f,attr,val):
if attr not in self.legal:
raise AttributeError( "A object has no attribute '%s'" %
attr)
self.__dict__[attr] = val
def __init__(self,x ):
self.y = x
I suspect most people who go into Python doing something like this
soon abandon it when they see how rarely it actually catches anything.
Carl Banks
Sep 4 '08 #7
On 4 ÓÅÎÔ, 22:59, Carl Banks <pavlovevide... @gmail.comwrote :
You can write code to guard against this if you want:

class A:
š š legal = set(["x"])
š š def __setattr__(sel f,attr,val):
š š š š if attr not in self.legal:
š š š š š š raise AttributeError( "A object has no attribute '%s'" %
attr)
š š š š self.__dict__[attr] = val
š š def __init__(self,x ):
š š š š self.y = x

I suspect most people who go into Python doing something like this
soon abandon it when they see how rarely it actually catches anything.

Carl Banks
'__slots__' is better:
class A(object):
__slots__ = set(["x"])
def __init__(self, x):
self.y = x

this will do the same, only faster
>>A(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in __init__
AttributeError: 'A' object has no attribute 'y'
Ivan Illarionov
Sep 4 '08 #8
On 4 §ã§Ö§ß§ä, 21:49, Bruno Desthuilliers
<bdesth.quelque ch...@free.quel quepart.frwrote :
Ivan Illarionov a ¨¦crit :
On 4 §ã§Ö§ß§ä, 22:59, Carl Banks <pavlovevide... @gmail.comwrote :
You can write code to guard against this if you want:
class A:
legal = set(["x"])
def __setattr__(sel f,attr,val):
if attr not in self.legal:
raise AttributeError( "A object has no attribute '%s'" %
attr)
self.__dict__[attr] = val
def __init__(self,x ):
self.y = x
I suspect most people who go into Python doing something like this
soon abandon it when they see how rarely it actually catches anything.
'__slots__' is better:

For which definition of "better" ? __slots__ are a mean to optimize
memory usage, not to restrict dynamism. Being able to dynamically add
arbitrary attributes is actually a feature, not a bug, and uselessly
restricting users from doing so is not pythonic. IOW : don't do that.
Carl's example is restricting dynamism in the same way as __slots__.
I've just suggested a better implementation. It is not me who
suggested dynamism restriction as a way to guard against errors.
Sep 4 '08 #9
On Sep 4, 3:15 pm, Ivan Illarionov <ivan.illario.. .@gmail.comwrot e:
On 4 ÓÅÎÔ, 22:59, Carl Banks <pavlovevide... @gmail.comwrote :
You can write code to guard against this if you want:
class A:
legal = set(["x"])
def __setattr__(sel f,attr,val):
if attr not in self.legal:
raise AttributeError( "A object has no attribute '%s'" % attr)
self.__dict__[attr] = val
def __init__(self,x ):
self.y = x
I suspect most people who go into Python doing something like this
soon abandon it when they see how rarely it actually catches anything.
Carl Banks

'__slots__' is better:
class A(object):
__slots__ = set(["x"])
def __init__(self, x):
self.y = x

this will do the same, only faster>>A(1)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in __init__
AttributeError: 'A' object has no attribute 'y'

However, if you subclass your version of A that uses __slots__, the
subclass will once again allow all attribute access, whereas if you
subclass my version of A that uses __getattr__, it will still be
restricted to the allowed symbols (unless you were to override the
list of symbols, which you probably would).

The latter behavior is less surprising and less dangerous, which
(besides the questionable usage) is the main reason using __slots__ is
not recommended for this purpose.

(Having said that, I do admit to using __slots__ for this purpose
once. But, the confusing aspects of __slots__ were managed by a
metaclass and hidden from the user.)
Carl Banks
Sep 4 '08 #10

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

Similar topics

7
1239
by: Frank Millman | last post by:
Hi all I want to control the assignment of a value to an attribute. Instead of allowing it to be changed directly, I want to enforce that a method is called, which will perform the assignment subject to various checks. From reading the manuals, this is one way to do it. class frank:
14
1978
by: bruce stockwell | last post by:
Using 'self' in classes seems pretty straight forward. My curiosity is why I have to use it. Shouldn't it be implied? If I create an instance of 'human' called 'bruce' and call the method 'blink' why do I have to pass bruce into the method e.g. class human: ...code def blink(self,times): for i in range(times): if self.eye_is_closed:
11
5050
by: Charles Krug | last post by:
I've a function that needs to maintain an ordered sequence between calls. In C or C++, I'd declare the pointer (or collection object) static at the function scope. What's the Pythonic way to do this? Is there a better solution than putting the sequence at module scope?
12
1955
by: Thomas Lotze | last post by:
Hi, I'm trying to figure out what is the most pythonic way to interact with a generator. The task I'm trying to accomplish is writing a PDF tokenizer, and I want to implement it as a Python generator. Suppose all the ugly details of toknizing PDF can be handled (such as embedded streams of arbitrary binary content). There remains one problem, though: In order to get random file access, the tokenizer should not simply spit out a series...
4
1799
by: Carl J. Van Arsdall | last post by:
It seems the more I come to learn about Python as a langauge and the way its used I've come across several discussions where people discuss how to do things using an OO model and then how to design software in a more "Pythonic" way. My question is, should we as python developers be trying to write code that follows more of a python standard or should we try to spend our efforts to stick to a more traditional OO model? For example, in...
33
2294
by: Gregory Petrosyan | last post by:
Buenos dias, amigos! I have to write _simple_ gui library, for embedding into game. My first attempt was to use XML: isn't it cute to describe ui in such a way: <window> <title>Hello World!</title> <image text="nice picture here" pos=... src=... /> <text opts=...> (some text here)
4
1171
by: telesphore4 | last post by:
Is there a better way to make the subclassing of built-in types stick? The goal is to have the the fields of a class behave like strings with extra methods attached. That is, I want the fact that the fields are not strings to be invisible to the client programmers. But I always want the extras to be there for the clients too. What I'm doing is subclassing str. Of course, whenever you then set mystr = 'a string' you loose the extra...
16
2531
by: Andy Dingley | last post by:
I'm trying to write rot13, but to do it in a better and more Pythonic style than I'm currrently using. What would you reckon to the following pretty ugly thing? How would you improve it? In particular, I don't like the way a three-way selection is done by nesting two binary selections. Also I dislike stating the same algorithm twice, but can't see how to parameterise them neatly. Yes, I know of .encode() and .translate(). No, I...
2
1856
by: wink | last post by:
Hello, I would like to know what would be considered the most Pythonic way of handling errors when dealing with files, solutions that seem reasonable using 2.5: ------- try: f = open('afile', 'r') content = f.read()
0
9589
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
9423
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
9865
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
8876
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...
1
7413
isladogs
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6675
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
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3967
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3567
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.