473,663 Members | 2,876 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

too dynamic - how to avoid?

mic
I've spent last hour trying to debug my code, when I found out that instead
of executing object's method I accidentaly overridden it with variable (see
below example). My stupid! But as the system becomes more complex, I begun
to wonder how to avoid such situations in the future. Does anybody have some
experiences about that?

Simple example:

class test:
def a(self, value):
print value
t = test()
t.a('my test') <= returns obviously 'my test'
t.a = 'my test' <= creates object's attribute a, so I'm loosing my method

Regards,

Michal
Jul 18 '05 #1
5 1584
mic wrote:
I've spent last hour trying to debug my code, when I found out that
instead of executing object's method I accidentaly overridden it with
variable (see below example). My stupid! But as the system becomes more
complex, I begun to wonder how to avoid such situations in the future.
Does anybody have some experiences about that?
Yes, and the experience is: it's not a problem in practice. Still,
if you disagree, Python gives you the tools to protect yourself -- read
on.

Simple example:

class test:
def a(self, value):
print value
t = test()
t.a('my test') <= returns obviously 'my test'
t.a = 'my test' <= creates object's attribute a, so I'm loosing my method


First of all, be sure to make your classes newstyle, e.g.
class test(object):
otherwise, by default, you get oldstyle classes, where compatibility
constraints mean most important new features just can't work right.

Now, limiting discussion to newstyle classes only:

in a class's dictionary there are two kinds of descriptors --
somewhat arbitrarily names 'data' and 'non-data' kinds of descriptors.

The 'non-data' kind, used for example for methods, are SPECIFICALLY
designed to be overridable per-instance. The 'data' kind aren't.

(Names are rather artificial; the real distinction is whether a
__set__ method is present in the descriptor -- if yes, it's data,
otherwise it's non-data -- calling it "setting-intercept" might
be clearer than calling it 'data'...!). Check it out...:

class c(object):
def a(self): pass
b = property(a)

descriptor 'a' is non-data, so it can be overridden in instances;
descriptor 'b' is data, so it cannot. E.g.:
x=c()
x.a=23
x.b=23 Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: can't set attribute


The 'property' type of descriptors isn't quite suitable for what
you want, of course, because even just ACCESSING x.b makes a CALL
to x.a. Rather, you want a new and different "nonrebindablem ethod"
type of descriptor whose __get__ is just like the function, while
its __set__ raises the exception. So, make such a type:

class norebind(object ):
def __init__(self, func): self.func = func
def __get__(self, *args): return self.func.__get __(*args)
def __set__(self, *args): raise TypeError

class c(object):
def a(self): pass
b = norebind(a)

There -- now, after x=c(), attempts to rebind x.b will raise a
TypeError, as you apparently wish. Note that you can code the
class as:

class c(object):
def a(self): pass
a = norebind(a)

so that there's no x.b -- just a non-rebindable x.a.
You won't need it in practice, but it's still a cool hack:-).

Alex

Jul 18 '05 #2
"mic" <al*****@onet.p l> writes:
I've spent last hour trying to debug my code, when I found out that instead
of executing object's method I accidentaly overridden it with variable (see
below example). My stupid! But as the system becomes more complex, I begun
to wonder how to avoid such situations in the future. Does anybody have some
experiences about that?


- use of decent naming schemes presumably helps (and if your class gets so big
that you can't remember what are attributes and what are methods refactoring
would probably be a good idea)

- if that's not enough you can always do something like override __setattr__,
to check that you don't overwrite instance methods, e.g. (UNTESTED):

import types
class bar:
...
def __setattr__(sel f, attr, value):
if isinstance(geta ttr(self, attr, None), types.MethodTyp e):
raise RuntimeError("T rying to overwrite method %s" % attr)
else setattr(self, attr, value)
- if you need this often, you could write a function or metaclass to avoid
duplicating the above in all classes where you feel you need it.
'as
Jul 18 '05 #3
"mic" <al*****@onet.p l> wrote:
I've spent last hour trying to debug my code, when I found out that instead
of executing object's method I accidentaly overridden it with variable (see
below example). My stupid! But as the system becomes more complex, I begun
to wonder how to avoid such situations in the future. Does anybody have some
experiences about that?

Simple example:

class test:
def a(self, value):
print value
t = test()
t.a('my test') <= returns obviously 'my test'
t.a = 'my test' <= creates object's attribute a, so I'm loosing my method


From this I can't discern whether you're asking a simple question or
want some sophisticated, nifty programming advice. I'm assuming you
just want some help using the interpreter and the overall programming
environment.

If something -whatever- is not quite as expected it's very important
to read the traceback (if there is one) from the interpreter output,
for example in this case trying to call t.a('my test') after t.a has
been bound to a string will result in some complaint from the
interpreter that type 'str' has no call method. It's also very a good
idea to include the traceback in usenet posts since that makes it
possible to receive more specific comments.

Another thing is that it's very handy to use the interactive
interpreter to test pieces of code that behave in unexpected ways.
Just try it out and check the output of your functions. It's not like
indexing an array out of bounds will make your complete system crash
or make it instable, Python is reasonably well defended against simple
mistakes.

The dir command is handy too, for example dir(t.a) will give some info
about what the interpreter thinks t.a is. Next, sprinkling your code
with print statements -turning it into a poor mans debugger system-
works very well for most of the mistakes of this calibre.

Please note that given the dynamic nature of Python the above code
snippet might be exactly what you want and there's no way for the
interpreter yet to do what you intend rather than what you code ;-)

Then there's the debugger inside Idle, but the strategies above are
sufficient in most cases, so that -at least in my case- it's almost
never necessary to use it. I mostly use Scite as an editor and have
pychecker* a single keypress away, but I only use it to doublecheck my
code after it runs as expected.

HTH,

Anton

* http://pychecker.sourceforge.net/

Jul 18 '05 #4
On Thu, 02 Oct 2003 11:56:49 +0200, mic wrote:
My stupid! But as the system becomes more complex, I begun
to wonder how to avoid such situations in the future. Does anybody have some
experiences about that?


1) Don't do it.
2) You can use a naming convention
a) Methods have verbs, variables don't: set_temperature , temperature
b) Prefix members with warts: x.temperature() x._temperature or
x.its_temperatu re
c) Your choice here
3) See #1, above

Pychecker doesn't seem to pick this up. I don't know about pylint.
I guess it might be something possible if you are talking methods
and attributes.

Tim
Jul 18 '05 #5
"mic" <al*****@onet.p l> writes:
I've spent last hour trying to debug my code, when I found out that instead
of executing object's method I accidentaly overridden it with variable (see
below example). My stupid! But as the system becomes more complex, I begun
to wonder how to avoid such situations in the future. Does anybody have some
experiences about that?


I don't understand how that could cause a problem. Why didn't you
immediately get a traceback with a message something like 'a is not
callable'?
John
Jul 18 '05 #6

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

Similar topics

1
2453
by: foldface | last post by:
Hi I'm working with a web site where 99% of the content is dynamic and words can be of any size, e.g. thiswouldbeavalidword. At the moment everything is done using inner tables, I want to move to a css type design. My issue is that I can't really use absolute positioning because, as I say, the words can be of any size, and I have no way of knowing how big the content is going to be. Plus I'd just like to avoid it anyway. I've used...
14
2223
by: Spare Change | last post by:
I am told that I can have a dynamic or static string array. So if I declare string dynamic; How do I add elements to dynamic and resize it ?
4
4421
by: Leslaw Bieniasz | last post by:
Cracow, 20.10.2004 Hello, As far as I understand, the generic programming basically consists in using templates for achieving a static polymorphism of the various code fragments, and their reuse for various template parameters. I wonder if there exist techniques for achieving a dynamic polymorphism using the generic programming. Is this possible? If yes, can anyone show me simple examples in C++
6
8203
by: chris | last post by:
Hi all, I need to know, what is the difference between dynamic memory allocation, and stack allocation ? 1. If I have a class named DestinationAddress, when should I use dynamic memory allocation to create object of that class ? 2. If it says "dynamic memory allocation", is it mean the following code : DestinationAddress* dest = new DestinationAddress(); // code 1
7
6283
by: Ford Desperado | last post by:
there is an application which issues a lot of simple dynamic queries against an Oracle database. If CURSOR_SHARING is set to FORCE, Oracle treats dynamic queries as static ones, for instance SELECT * FROM SALES WHERE CUSTOMER_ID=12345 Oracle will replace 12345 with a parameter SELECT * FROM SALES WHERE CUSTOMER_ID=:SYS_0 then it will provide 12345 (there is a very convenient setting CURSOR_SHARING just for that). Next time a similar query...
3
3973
by: Leo J. Hart IV | last post by:
OK, here's another question for the experts: I am building a multi-step (3 steps actually) form using a panel for each step and hiding/displaying the appropriate panel/panels depending on which step you're on. This all works fine, but I ran into some trouble when I started creating controls dynamically in my code-behind file. Each panel contains a table which is filled with various radio buttons, text fields and the such which are...
1
1203
by: Luis Ferrao | last post by:
Hi, To understand the problem, a small description of the situation should be provided: I have a Field Control that is made of a one row table with three columns. The table width is 100%, the first column is 40% and the other two have a width of 30%. The middle cell has a TextField with 100% width followed by a requiredValidator (display set to dynamic).
11
3040
by: toton | last post by:
Hi, I have little confusion about static memory allocation & dynamic allocation for a cluss member. I have class like class Bar{ public: explicit Bar(){ cout<<"bar default"<<endl; }
9
3621
by: Tarscher | last post by:
hi all, I have this seemingly simple problem. I have lost a lot of time on it though. When a user selects a value from a dropdownlist (static control) a dynamic control is generated. I have to create the dynamic controls in the OnInit stage of the lifecycle. Since data from static controls is not yet available in the OnInit stage I can't know what dynamic control I have to create.
0
8345
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
8858
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
8771
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
8548
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
7371
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
6186
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
4182
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
4349
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2000
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.