473,804 Members | 2,020 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

handling many default values

My class MyClass reuses many default parameters
with a small number of changes in each instance.
For various reasons I decided to put all the
parameters in a separate Params class, instances
of which reset the default values based on keyword
arguments, like this:

class Params:
def __init__(self,* *kwargs):
#set lots of default values
...
#set the deviations from defaults
self.__dict__.u pdate(kwargs)

Is this a reasonable approach overall?
(Including the last line.)

Thanks,
Alan Isaac
Nov 10 '06 #1
10 1557
At Friday 10/11/2006 14:11, Alan G Isaac wrote:
>My class MyClass reuses many default parameters
with a small number of changes in each instance.
For various reasons I decided to put all the
parameters in a separate Params class, instances
of which reset the default values based on keyword
arguments, like this:

class Params:
def __init__(self,* *kwargs):
#set lots of default values
...
#set the deviations from defaults
self.__dict__.u pdate(kwargs)

Is this a reasonable approach overall?
(Including the last line.)
I'm not sure what you want to do exactly, but a class attribute acts
as a default instance attribute.

class A(object):
x = 0
y = 20
def __init__(self, x=None, y=None):
if x is not None: self.x = x
if y is not None: self.y = y

class B(A):
z = 3
def __init__(self, x=None, y=None, z=None):
A.__init__(self , x, y)
if z is not None: self.z = z

a = A(1)
print "a.x=",a.x
print "a.y=",a.y

b = B(z=8)
print "b.x=",b.x
print "b.y=",b.y
print "b.z=",b.z

output:

a.x= 1
a.y= 20
b.x= 0
b.y= 20
b.z= 8
--
Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
Nov 10 '06 #2
At Friday 10/11/2006 14:11, Alan G Isaac wrote:
class Params:
def __init__(self,* *kwargs):
#set lots of default values
...
#set the deviations from defaults
self.__dict__.u pdate(kwargs)

Is this a reasonable approach overall?
(Including the last line.)

"Gabriel Genellina" wrote in message
news:ma******** *************** *************** *@python.org...
I'm not sure what you want to do exactly, but a class attribute acts
as a default instance attribute.
Yes. I am sorry my question was not clearer.
There are *many* parameters,
and the list can change,
so I want to avoid listing them all in the Param class's __init__ function,
using the strategy above.

Q1: Is this approach reasonable?
(This is a newbie question about unforseen hazards.)
Q2: Is it horrible design to isolate the parameters in a separate class?
(Comment: currently several classes may rely on (parts of) the same
parameter set.)

Thanks,
Alan Isaac
Nov 11 '06 #3
On Fri, 10 Nov 2006 17:11:24 +0000, Alan G Isaac wrote:
My class MyClass reuses many default parameters
with a small number of changes in each instance.
Let me see that I understand. Are you doing something like this?

# Class takes a lot of arguments
a = MyClass(0, 1, 2, 3, 4, 5, ..., 99)
# and instances vary only by one or two of those args
b = MyClass(0, 2, 2, 3, 4, 5, ..., 99)
c = MyClass(0, 3, 2, 3, 4, 5, ..., 99)
d = MyClass(0, 4, 2, 3, 4, 5, ..., 99)
e = MyClass(0, 5, 2, 3, 4, 5, ..., 99)
....
z = MyClass(0, 26, 2, 3, 4, 5, ..., 99)

If that's the case, I'd seriously rethink your class design. It is hard to
advise a better design without knowing more about the class, but I'd be
surprised if you can't use subclassing to reduce the number of parameters
needed. E.g.:

class MyClass(object) :
def __init__(self, arg0):
self.arg0 = arg0
# now fill in arguments 1 through 99 with sensible values

class MyClass2(MyClas s):
def __init__(self, arg1):
"""Just like MyClass, but arg0 has a fixed value and arg1 varies"""
super(MyClass, self).__init__( "fixed value")
self.arg1 = arg1

and so on for as many subclasses that you need.

In the same way, perhaps you can group those arguments. E.g. instead of
this:
class WordProcessingD oc(object):
def __init__(self, page_width, page_height, left_margin,
right_margin, top_margin, bottom_margin, font_face,
font_size, font_style, line_size, justification): # and many more
# and many, many more arguments
pass
Create some classes, and pass instances of them to the main class:

class CharStyle(objec t):
def __init__(self, font_face, font_size, font_style):
pass
class PageStyle(objec t):
def __init__(self, width, height, left, right, top, bottom):
pass

class WordProcessingD oc(object):
def __init__(self, pagestyle, charstyle, paragraphstyle) :
pass
For various reasons I decided to put all the
parameters in a separate Params class, instances
of which reset the default values based on keyword
arguments, like this:

class Params:
def __init__(self,* *kwargs):
#set lots of default values
...
#set the deviations from defaults
self.__dict__.u pdate(kwargs)

Is this a reasonable approach overall?
(Including the last line.)
(1) If there really is no alternative to a class with many arguments;
(2) and instances can vary those arguments unpredictably;

then this approach seems reasonable to me. But I really suggest you
rethink your class design.

--
Steven.

Nov 11 '06 #4

Alan Isaac wrote:
At Friday 10/11/2006 14:11, Alan G Isaac wrote:
>class Params:
def __init__(self,* *kwargs):
#set lots of default values
...
#set the deviations from defaults
self.__dict__.u pdate(kwargs)
>
>Is this a reasonable approach overall?
>(Including the last line.)


"Gabriel Genellina" wrote in message
news:ma******** *************** *************** *@python.org...
I'm not sure what you want to do exactly, but a class attribute acts
as a default instance attribute.

Yes. I am sorry my question was not clearer.
There are *many* parameters,
and the list can change,
so I want to avoid listing them all in the Param class's __init__ function,
using the strategy above.

Q1: Is this approach reasonable?
(This is a newbie question about unforseen hazards.)
Q2: Is it horrible design to isolate the parameters in a separate class?
(Comment: currently several classes may rely on (parts of) the same
parameter set.)

Thanks,
Alan Isaac
Hi,
I kind of had a similar problem when I was developing a 3d OO engine.
I had many
bigger things composed of lots of little things, and a lot of code was
spent
initializing the little things in constructors.

So I just passed a reference of the bigger thing to the little thing in
its constructor, thus saving a lot
of parameter passing and variable setup and copying. In the following
example, big is passed to
little's constructor, instead of all of big's variables.

ie.
class big:
def __init__(self):
self.v1 = ...
self.v2 = ...
self.objects = []
def assemble(self):
self.objects.ap pend(little(sel f, 1))
self.objects.ap pend(little(sel f,2))

class little:
def __init__(self, big, n):
self.big = big # Now little has access to v1, v2 by self.big.v1
etc
self.n = n # This makes it different
def a_function(self ):
do_something(se lf.big.v1, self.big.v2)

Nov 11 '06 #5
"Alan Isaac" <ai****@america n.eduwrites:
There are *many* parameters, and the list can change, so I want to
avoid listing them all in the Param class's __init__ function, using
the strategy above.

Q1: Is this approach reasonable?
(This is a newbie question about unforseen hazards.)
Q2: Is it horrible design to isolate the parameters in a separate class?
(Comment: currently several classes may rely on (parts of) the same
parameter set.)
It's a bad design smell to have functions that accept large numbers of
parameters, many of them optional. Such an interface is difficult to
document, maintain and test.

You should certainly be examining such code and seeing how much of it
can be implemented instead as functions with small, well-defined
parameter lists. This may mean writing more functions, or more layers
of functions, or more classes, or whatever; but having a result that
uses small, well-defined interfaces is a valuable property.

--
\ "The number of UNIX installations has grown to 10, with more |
`\ expected." -- Unix Programmer's Manual, 2nd Ed., 12-Jun-1972 |
_o__) |
Ben Finney

Nov 11 '06 #6
Ben Finney wrote:
"Alan Isaac" <ai****@america n.eduwrites:
There are *many* parameters, and the list can change, so I want to
avoid listing them all in the Param class's __init__ function, using
the strategy above.

Q1: Is this approach reasonable?
(This is a newbie question about unforseen hazards.)
Q2: Is it horrible design to isolate the parameters in a separate class?
(Comment: currently several classes may rely on (parts of) the same
parameter set.)

It's a bad design smell to have functions that accept large numbers of
parameters, many of them optional. Such an interface is difficult to
document, maintain and test.

You should certainly be examining such code and seeing how much of it
can be implemented instead as functions with small, well-defined
parameter lists. This may mean writing more functions, or more layers
of functions, or more classes, or whatever; but having a result that
uses small, well-defined interfaces is a valuable property.
So I guess you prefer the (os.system, os.spawn*, os.popen*, popen2.*,
commands.*) kitchen sink than the single versatile subprocess.Pope n
class, right ? I respectfully disagree, and I'm all for
one-class-does-it-all, as long as most parameters are optional and the
default values address the most typical/reasonable case.

To answer to OP's question, your approach is totally reasonable and
well-known; the csv.Dialect class for example is exactly this, a
parameter-holding class.

George

Nov 11 '06 #7
"Steven D'Aprano" wrote
(1) If there really is no alternative to a class with many arguments;
(2) and instances can vary those arguments unpredictably;
then this approach seems reasonable to me. But I really suggest you
rethink your class design.
Thanks to all who replied and to George for his specific example.
Steve's comments seem to summarize the overall sentiment:
there is no *general* objection, but I should make sure my
specific implementation really profits from a parameter holding class
(rather than, e.g., a super class in which appropriate defaults are set).
I believe this is the case, since the many parameters can vary
arbitrarily and do not fall into neat groupings.

Also, as an aside, no one objected to using
self.__dict__.u pdate(kwargs)
in the __init__ function of the parameter holding class.

Thanks,
Alan
Nov 11 '06 #8
Alan Isaac wrote:
Also, as an aside, no one objected to using
self.__dict__.u pdate(kwargs)
in the __init__ function of the parameter holding class.
It is a common trick, also shown in the Python cookbook, IIRC. If you
are anal about
double underscores, you can also use

vars(self).upda te(kwargs)

Michele Simionato

Nov 13 '06 #9
At Monday 13/11/2006 13:33, Michele Simionato wrote:
>Alan Isaac wrote:
Also, as an aside, no one objected to using
self.__dict__.u pdate(kwargs)
in the __init__ function of the parameter holding class.

It is a common trick, also shown in the Python cookbook, IIRC. If you
are anal about
double underscores, you can also use

vars(self).upd ate(kwargs)
Not good - that relies on vars() returning the actual __dict__.
From <http://docs.python.org/lib/built-in-funcs.html>:
"The returned dictionary should not be modified: the effects on the
corresponding symbol table are undefined."
--
Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
Nov 13 '06 #10

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

Similar topics

115
7247
by: J | last post by:
I've run CSSCheck on my style sheets and I always get a warning similar to this: "font: bold 9pt/100% sans-serif Warning: Absolute length units should not generally be used on the Web ..." Yet if I use 'x-small' instead of 9pt, I get bigger type on IE6 and smaller type on Mozilla. My choices seem to be:
4
332
by: Brendan McLoughlin | last post by:
Hi, I am looking for opinions and alternatives for handling null values in a data object which reads a record from a database table. This object will have properties which will be populated from the DB table columns, standard enough. But what about the instance where a column could be null.
2
5128
by: xAvailx | last post by:
I have a requirement that requires detection of rows deleted/updated by other processes. My business objects call stored procedures to create, read, update, delete data in a SQL Server 2000 data store. I've done a fair amount of research on concurrency handling in newsgroups and other resources. Below is what I've come up as a standard for handling concurrency thru stored procedures. I am sharing with everyone so I can get some comments...
2
2000
by: CSDunn | last post by:
Hello, I need some assistance with error handling in an Access 2003 Project form. The project is has a data source connection to a SQL Server 2000 database. The main form is named ‘frmSelectByTest', and its subform's ‘Name' and ‘Source Object' properties are ‘frmSelectByTestSub'. The ‘Default View' on the main form is ‘Single Form', and on the sub form is ‘Continuous Forms'. The users select the name of a test (uniquely identified by a...
5
1507
by: Asha | last post by:
greetings, i'm converting my value to int value using int32.parse() the problem is that, if its an empty value it returns me an error. what can i do to handle this error besides using a if condition to handle it.
4
7622
by: James Radke | last post by:
Hello, I am looking for guidance on best practices to incorporate effective and complete error handling in an application written in VB.NET. If I have the following function in a class module (note that this class module represents the business layer of code NOT the gui layer): Public Function Test(ByVal Parm1 As Integer, ByVal Parm2 As Integer) As SqlDataReader ' Declare the SQL data layer class Dim oSQL As New...
6
5952
by: Charlie Brown | last post by:
When checking for NULL values from a database, normally I would use If Not row("NetSales") Is DBNull.Value Then NetSales = row("NetSales") End If However, if I use a typed dataset then I can't check for NULL the same way
4
1678
by: Cirene | last post by:
I'm designing my db for a online Scheduling web application. How do you suggest I handle reoccuring events? In my appointments table should I just add 1 record for EACH time the appointment will appear (and link all "related" appts with a key field)? Or should I just have 1 record for each appointment, whether it's reoccuring or not. I downloaded the RadScheduler app and noticed in their sample db they had a "RecurrenceRule" and...
9
2274
by: Daniel Smedegaard Buus | last post by:
Hey all :) I was wondering about the $error_types (I particularly notice the 's' suffix when reading the manual) parameter for 'set_error_handler()': Can be used to mask the triggering of the error_handler function just like the error_reporting ini setting controls which errors are shown. Without this mask set the error_handler will be called for every error regardless to the setting of the error_reporting setting.
0
9716
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
9595
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
10604
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
10101
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...
1
7643
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
6870
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
5536
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...
2
3837
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3005
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.