473,387 Members | 1,664 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,387 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 1275
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: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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,...

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.