473,383 Members | 1,815 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,383 software developers and data experts.

How much introspection is implementation dependent?

Hello,

I wanted to automagically generate an instance of a class from a
dictionary--which might be generated from yaml or json. I came up with this:
# automagical constructor
def construct(cls, adict):
dflts = cls.__init__.im_func.func_defaults
vnames = cls.__init__.im_func.func_code.co_varnames

argnames = vnames[1:-len(dflts)]
argvals = [adict.pop(n) for n in argnames]

return cls(*argvals, **adict)
I'm wondering, I did a lot of introspection here. How much of this
introspection can I count on in other implementations. Is this a
byproduct of CPython? Will all classes have these attributes, even
classes imported from shared objects? It would be nice to rely on these
things.

<asideI know pyaml advertises the ability to do this, but, much to my
annoyance, I found it never actually calls __init__() of YAMLObject
subclasses, but this is another topic altogether. </aside>

Below is the example (optional reading).

James

==

#! /usr/bin/env python

# automagical constructor
def construct(cls, adict):
dflts = cls.__init__.im_func.func_defaults
vnames = cls.__init__.im_func.func_code.co_varnames

argnames = vnames[1:-len(dflts)]
argvals = [adict.pop(n) for n in argnames]

return cls(*argvals, **adict)
def test():

class C(object):
def __init__(self, arg1, arg2, kwa3=3):
self.argsum = arg1 + arg2
self.kwsum = kwa3
def __str__(self):
return "%s & %s" % (self.argsum, self.kwsum)

# now a dict for autmagical generation
adict = {'arg1':1, 'arg2':2, 'kwa3':42}

print '======== test 1 ========'
print adict
print construct(C, adict)

adict = {'arg1':1, 'arg2':2}
print
print '======== test 2 ========'
print adict
print construct(C, adict)

if __name__ == "__main__":
test()
Feb 3 '07 #1
3 1335
On Feb 2, 6:56 pm, James Stroud <jstr...@mbi.ucla.eduwrote:
Hello,

I wanted to automagically generate an instance of a class from a
dictionary--which might be generated from yaml or json. I came up with this:

(snip)

==

#! /usr/bin/env python

# automagical constructor
def construct(cls, adict):
dflts = cls.__init__.im_func.func_defaults
vnames = cls.__init__.im_func.func_code.co_varnames

argnames = vnames[1:-len(dflts)]
argvals = [adict.pop(n) for n in argnames]

return cls(*argvals, **adict)

def test():

class C(object):
def __init__(self, arg1, arg2, kwa3=3):
self.argsum = arg1 + arg2
self.kwsum = kwa3
def __str__(self):
return "%s & %s" % (self.argsum, self.kwsum)

# now a dict for autmagical generation
adict = {'arg1':1, 'arg2':2, 'kwa3':42}

print '======== test 1 ========'
print adict
print construct(C, adict)

adict = {'arg1':1, 'arg2':2}
print
print '======== test 2 ========'
print adict
print construct(C, adict)

if __name__ == "__main__":
test()
What's the point of this ? You can call C simply by C(**adict). Am I
missing something ?

George

Feb 3 '07 #2
George Sakkis wrote:
On Feb 2, 6:56 pm, James Stroud <jstr...@mbi.ucla.eduwrote:
>Hello,

I wanted to automagically generate an instance of a class from a
dictionary--which might be generated from yaml or json. I came up with this:

(snip)

==

#! /usr/bin/env python

# automagical constructor
def construct(cls, adict):
dflts = cls.__init__.im_func.func_defaults
vnames = cls.__init__.im_func.func_code.co_varnames

argnames = vnames[1:-len(dflts)]
argvals = [adict.pop(n) for n in argnames]

return cls(*argvals, **adict)

def test():

class C(object):
def __init__(self, arg1, arg2, kwa3=3):
self.argsum = arg1 + arg2
self.kwsum = kwa3
def __str__(self):
return "%s & %s" % (self.argsum, self.kwsum)

# now a dict for autmagical generation
adict = {'arg1':1, 'arg2':2, 'kwa3':42}

print '======== test 1 ========'
print adict
print construct(C, adict)

adict = {'arg1':1, 'arg2':2}
print
print '======== test 2 ========'
print adict
print construct(C, adict)

if __name__ == "__main__":
test()

What's the point of this ? You can call C simply by C(**adict). Am I
missing something ?

George
Maybe there is something wrong with my python.

pyclass C:
.... def __init__(a, b, c=4):
.... print a,b,c
....
pyC(**{'a':10, 'b':5, 'c':4})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() got multiple values for keyword argument 'a'
James
Feb 3 '07 #3
George Sakkis wrote:
On Feb 2, 6:56 pm, James Stroud <jstr...@mbi.ucla.eduwrote:
>Hello,

I wanted to automagically generate an instance of a class from a
dictionary--which might be generated from yaml or json. I came up with this:

(snip)

==

#! /usr/bin/env python

# automagical constructor
def construct(cls, adict):
dflts = cls.__init__.im_func.func_defaults
vnames = cls.__init__.im_func.func_code.co_varnames

argnames = vnames[1:-len(dflts)]
argvals = [adict.pop(n) for n in argnames]

return cls(*argvals, **adict)

def test():

class C(object):
def __init__(self, arg1, arg2, kwa3=3):
self.argsum = arg1 + arg2
self.kwsum = kwa3
def __str__(self):
return "%s & %s" % (self.argsum, self.kwsum)

# now a dict for autmagical generation
adict = {'arg1':1, 'arg2':2, 'kwa3':42}

print '======== test 1 ========'
print adict
print construct(C, adict)

adict = {'arg1':1, 'arg2':2}
print
print '======== test 2 ========'
print adict
print construct(C, adict)

if __name__ == "__main__":
test()

What's the point of this ? You can call C simply by C(**adict). Am I
missing something ?

George
Never mind. You're right.

pyclass C(object):
.... def __init__(self, a, b, c=4):
.... print a,b,c
....
pyC(**adict)
10 5 4
<__main__.C object at 0x762530>
I guess I thought that, were it this easy, it would have been done in pyaml.

James
Feb 3 '07 #4

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

Similar topics

4
by: Benjamin Rutt | last post by:
I'm trying to learn about introspection in Python. my ultimate goal is to be able to build a module "text database" of all modules that are in the sys.path, by discovering all candidate modules...
4
by: sj | last post by:
I believe the type "list" is implemented as an array of pointers. Thus, random access is an O(1) operation while insertion/deletion is an O(n) operation. That said, I have the following questions:...
0
by: Steven T. Hatton | last post by:
I suspect the core language is not the level at which introspection should be implemented in C++. That has been the choice of C#, and Java. Both of these languages made some trade-offs to...
4
by: Steven T. Hatton | last post by:
Has there been any substantial progress toward supporting introspection/reflection in C++? I don't intend to mean it should be part of the Standard. It would, nonetheless, be nice to have a...
1
by: James Geurts | last post by:
Hi, Can someone tell me how to test if a field is a const? I am using the FxCop introspection engine, but I suppose I could use reflection if required. for example, the following would return...
8
by: R. Bernstein | last post by:
In doing the extension to the python debugger which I have here: http://sourceforge.net/project/showfiles.php?group_id=61395&package_id=175827 I came across one little thing that it would be nice...
14
by: embeddedc | last post by:
Hi, Referring to C90, is there somewhere published a list of all parts of the standard where the behavior is not specified or implementation dependent? If not and I want to find all such...
14
by: Dave Rahardja | last post by:
Is there a way to generate a series of statements based on the data members of a structure at compile time? I have a function that reverses the endianness of any data structure: /// Reverse...
11
by: EricGoogle | last post by:
Hello All, I am trying to figure out a how to get a variable's name from code. Ex: var MYVAR = 3; alert( ????? ); OUTPUT: "MYVAR"
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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...

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.