473,805 Members | 1,963 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 AutoInitAttribu tes(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*********@jab ber.i-pobox.net
GPG: 0xF534E231
Oct 17 '07 #1
4 1296
On 10/17/07, Thomas Wittek <ma**@gedankenk onstrukt.dewrot e:
>
Writing such constructors for all classes is very tedious.
So I subclass them from this base class to avoid writing these constructors:

class AutoInitAttribu tes(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__=fa ke_str)
str(u)
Does SQLAlchemy let you get a list of column names? If so you could do:

class AutoInitAttribu tes(object):
def __init__(self, **kwargs):
valid_attrs = set(get_column_ names_from_sqla lchemy())
# 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*********@jab ber.i-pobox.net
GPG: 0xF534E231
Oct 17 '07 #3
Andrew Durdin <ad*****@gmail. comwrote:
On 10/17/07, Thomas Wittek <ma**@gedankenk onstrukt.dewrot e:

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

class AutoInitAttribu tes(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__=fa ke_str)
str(u)
....and, if you did, that would be totally harmless (in a new-style class
as shown by the OP):
>>class AutoInitAttribu tes(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(AutoInitAt tributes): pass
....
>>def fake_str(self):
.... return "not a User"
....
>>u = User(__str__=fa ke_str)
str(u)
'<__main__.Use r 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.activestat e.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 "overwritin g" issue MIGHT possibly be a (minor) annoyance.
Alex
Oct 17 '07 #4
On 10/17/07, Alex Martelli <al***@mac.comw rote:
>
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
2446
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 UML, and using automatic code generation to make Python APIs, XML I/O etc. (more below). We can be found at http://www.ccpn.ac.uk/index.html As a general point, automtic code generation would seem like a good idea in special cases where:
9
1573
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
5907
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 bitset<64>, but I know that STL has no virtual destructor. Can I get around this by calling the baseclass destructor explicitly in my derived class? Is there another way to get all of the bitset<64> functionality without rewriting a lot of...
4
1671
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. As far as I can see it is only difficult. Is it harmful if done correctly? If XHTML 1.0 Strict is served as text/html with a DOCTYPE declaration but without an XML declaration then it should be rendered in
0
1273
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 it generates -- they embed the full path to the working copy of the sources, which, beyond just being ugly, would be pretty annoying for a collaborative project (each collaborator's copy would produce documentation
5
2296
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 { double arr; }
16
1184
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 ? CopyByReferenceError: Variable b refers to variable a, so please do not change variable a. Does such a module exist? Would it be possible to code such a module?
2
3896
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
1701
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 : public virtual base
0
9596
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
10607
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
10359
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
10364
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,...
1
7645
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
6875
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
5677
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4317
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
3
3007
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.