473,288 Members | 1,729 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,288 software developers and data experts.

Inheriting automatic attributes initializer considered harmful?

Hi!

I'm relatively new to Python, so maybe there is an obvious answer to my
question, that I just didn't find, yet.

I've got quite some classes (from a data model mapped with SQL-Alchemy)
that can be instatiated using kwargs for the attribute values. Example:

class User(object):
def __init__(self, name=None):
self.name = name

u = User(name="user name")

Writing such constructors for all classes is very tedious.
So I subclass them from this base class to avoid writing these constructors:

class AutoInitAttributes(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
getattr(self, k) # assure that the attribute exits
setattr(self, k, v)

Is there already a standard lib class doing (something like) this?
Or is it even harmful to do this?
Although I cannot see any problems with it, I feel very unsafe about
that, because I've not seen this (in the few lines from some tutorials)
before.

Regards
--
Thomas Wittek
Web: http://gedankenkonstrukt.de/
Jabber: st*********@jabber.i-pobox.net
GPG: 0xF534E231
Oct 17 '07 #1
4 1270
On 10/17/07, Thomas Wittek <ma**@gedankenkonstrukt.dewrote:
>
Writing such constructors for all classes is very tedious.
So I subclass them from this base class to avoid writing these constructors:

class AutoInitAttributes(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
getattr(self, k) # assure that the attribute exits
setattr(self, k, v)

Is there already a standard lib class doing (something like) this?
Or is it even harmful to do this?
It depends on your kwargs and where they're coming from. You could do
something like this, for example:

def fake_str(self):
return "not a User"

u = User(__str__=fake_str)
str(u)
Does SQLAlchemy let you get a list of column names? If so you could do:

class AutoInitAttributes(object):
def __init__(self, **kwargs):
valid_attrs = set(get_column_names_from_sqlalchemy())
# Only set valid attributes, ignoring any other kwargs
for k in set(kwargs.keys()) & valid_attrs:
setattr(self, k, kwargs[k])

Andrew
Oct 17 '07 #2
Andrew Durdin:
>Is there already a standard lib class doing (something like) this?
Or is it even harmful to do this?

It depends on your kwargs and where they're coming from.
They should come from my own code.
Does SQLAlchemy let you get a list of column names?
Generellay, it does.
But it also generates some additional attributes dynamically that are
not directly defined as columns.
So, restricting the attributes to the columns would be too strict.

Thanks!
--
Thomas Wittek
Web: http://gedankenkonstrukt.de/
Jabber: st*********@jabber.i-pobox.net
GPG: 0xF534E231
Oct 17 '07 #3
Andrew Durdin <ad*****@gmail.comwrote:
On 10/17/07, Thomas Wittek <ma**@gedankenkonstrukt.dewrote:

Writing such constructors for all classes is very tedious.
So I subclass them from this base class to avoid writing these constructors:

class AutoInitAttributes(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
getattr(self, k) # assure that the attribute exits
setattr(self, k, v)

Is there already a standard lib class doing (something like) this?
Or is it even harmful to do this?

It depends on your kwargs and where they're coming from. You could do
something like this, for example:

def fake_str(self):
return "not a User"

u = User(__str__=fake_str)
str(u)
....and, if you did, that would be totally harmless (in a new-style class
as shown by the OP):
>>class AutoInitAttributes(object):
.... def __init__(self, **kwargs):
.... for k, v in kwargs.items():
.... getattr(self, k) # assure that the attribute exits
.... setattr(self, k, v)
....
>>class User(AutoInitAttributes): pass
....
>>def fake_str(self):
.... return "not a User"
....
>>u = User(__str__=fake_str)
str(u)
'<__main__.User object at 0x635f0>'
>>>
fake_str is not called, because special-method lookup occurs on the
TYPE, *NOT* on the instance.

The OP's idea is handy for some "generic containers" (I published it as
the "Bunch" class back in 2001 in
<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308>, and I
doubt it was original even then); it's not particularly recommended for
classes that need to have some specific *NON*-special methods, because
then the "overwriting" issue MIGHT possibly be a (minor) annoyance.
Alex
Oct 17 '07 #4
On 10/17/07, Alex Martelli <al***@mac.comwrote:
>
fake_str is not called, because special-method lookup occurs on the
TYPE, *NOT* on the instance.
So it does; I'd forgotten that. I need to remember to actually check
that the code does what I think it does before posting it on c.l.p
:-|

Andrew
Oct 18 '07 #5

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

Similar topics

0
by: Rasmus Fogh | last post by:
Someone raised the question of automatic code generation a few weeks back. And yes, we (CCPN) are using automatic Python code generation in a major way. Basically we are making data models in...
9
by: mike420 | last post by:
map(lambda f: f(1), ) Oh, OK, it was a typo (1 instead of i). I take it all back (for now). It was an honest mistake, not a troll! Still, I think it should be instead of
29
by: shaun roe | last post by:
I want something which is very like a bitset<64> but with a couple of extra functions: set/get the two 32 bit words, and conversion to unsigned long long. I can do this easily by inheriting from...
4
by: Pete Forman | last post by:
Ian Hickson's essay at http://www.hixie.ch/advocacy/xhtml and many others argue that XHTML served as text/html should be considered harmful. I'm looking for any evidence that this is really so. ...
0
by: Terry Hancock | last post by:
I've been trying to use "happydoc" to document a source tree that I'm working on. It does pretty much what I want, except: Version 2.1: Creates a weird directory structure for the HTML pages...
5
by: Wu | last post by:
Hi there, I was wondering whether there is a way to use array initializer syntax to initialize a non-static array member in a class in C++. In particular, if I have a class Foo: class Foo {...
16
by: Niels L Ellegaard | last post by:
Is there a module that allows me to find errors that occur due to copy by reference? I am looking for something like the following: Traceback (most recent call last): File "<stdin>", line 1, in...
2
by: dj3vande | last post by:
Is this code, as the complete contents of a translation unit, valid C90 that initializes the struct foo to contain copies of the values passed to bar()? -------- struct foo { int i; void *v;...
4
by: AalaarDB | last post by:
struct base { int x, y, z; base() {x = 0; y = 0; z = 0;}; base(int x1, int y1, int z1) {x = x1; y = y1; z = z1;}; }; struct intermediate1 : public virtual base {}; struct intermediate2 :...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

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.