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

Generating modul classes with eval

Hello!

I was fooling around with creating classes for a module with eval,
something like:

MyModule.py:

class Base:
init(self, name):
self._name = name

for myclass in ['A', 'B', 'C']:
code="class %s(Base):\n\tinit(self, name='%s')\n\t\tsuper(%s,
self).__init(name=name)\n"%dict(myclass, myclass.lower(), myclass())
... codeop and eval stuff ...
a=A()
print a

that gives: <class '__main__.A'>, but I want MyModule.A ;-)

Can someone give me a hint how to create classes in a module with eval
and codeop so that they exist like the code was written in?

Thanks,
AXEL.

Jul 18 '05 #1
4 1427
Axel Straschil wrote:
Hello!

I was fooling around with creating classes for a module with eval,
something like:

MyModule.py:

class Base:
init(self, name):
self._name = name

for myclass in ['A', 'B', 'C']:
code="class %s(Base):\n\tinit(self, name='%s')\n\t\tsuper(%s,
self).__init(name=name)\n"%dict(myclass, myclass.lower(), myclass())
... codeop and eval stuff ...
a=A()
print a

that gives: <class '__main__.A'>, but I want MyModule.A ;-)

Can someone give me a hint how to create classes in a module with eval
and codeop so that they exist like the code was written in?

Thanks,
AXEL.

You could try just importing the module - then, when it runs, its name
won't be "__main__" but "MyModule".

regards
Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005 http://www.python.org/pycon/2005/
Steve Holden http://www.holdenweb.com/
Jul 18 '05 #2
On Wed, 02 Feb 2005 20:49:07 +0000, Axel Straschil wrote:

You are doing several things wrong.
I was fooling around with creating classes for a module with eval,
You shouldn't create classes with eval, because you don't need to.

"class" isn't a declaration, it is an executable statement that creates
new classes. We'll get into that momentarily...
something like:

MyModule.py:

class Base:
init(self, name):
self._name = name
Your "init" function needs to be spelled "__init__", or it will not be
automatically called.

You also did not correctly use "def" to create your function. When posting
to the newsgroup, try to use real code that you have actually executed.
that gives: <class '__main__.A'>, but I want MyModule.A ;-)


No, it won't, since your code has syntax errors in it. Post the code you
actually ran.

That said, "__main__" indicates you ran it in the interactive shell. That
is correct, and won't change. Also, the name printing the class gives is
only very rarely important; overall you shouldn't be using that.

I'll start with giving you this:

-------

import sys
module = sys.modules[__name__]

class Base:
def __init__(self, name):
self._name = name

for myclass in ['A', 'B', 'C']:
class Tmp(Base):
myname = myclass
def __init__(self):
Base.__init__(self, self.myname)

setattr(module, myclass, Tmp)

-------

Note that we don't need eval anywhere.

But I'd suggest that this is more likely what you want:

-------

class Base:
def __init__(self, name):
self._name = name

myClasses = {}

for className in ['A', 'B', 'C']:
class Tmp(Base):
myname = className
def __init__(self):
Base.__init__(self, self.myname)

myClasses[className] = Tmp

-------

Adding things straight to modules is rarely worth it; you're better off
just collecting them somewhere.

There are too many differences to go over here between my code and yours,
so if you have questions, please ask. One of the reasons you don't want
eval is that I had to give up trying to read your class code!

Finally, while such generated classes do have their use, I'd ask what you
are planning to do with this; odds are, you don't need it.

In general, unless you are using "eval" to literally execute user supplied
input, you *almost* certainly don't need it.

A downside of my approach is that printing all three classes will say the
class name is "Tmp". Since, as I said, you really shouldn't care about
that, I don't care to try to fix it :-) If you can provide a compelling
reason why you need that, somebody here can help you with that.
Jul 18 '05 #3
On Wed, 02 Feb 2005 16:20:41 -0500, Jeremy Bowers wrote:
That said, "__main__" indicates you ran it in the interactive shell.


Or ran it directly on the command line. Duh. I thought that clause really
loudly, but I guess I never actually typed it.
Jul 18 '05 #4
Hello!
Note that we don't need eval anywhere.


Uuups, that looks realy cool! Thanks for that!

Im fooling around with generating html-tags. As there are only two kind
of html tags, one who can nest chields, and one who cant, i wantet to
play arround with something like:

I've got two base classes, _Tag and _ContainerTag (for tags which can
nest tags). Instead of getting an htmltag with _Tag(name='html'), I
want to have a class for each html-tag. So, I thought of creating that
classes dynamicly.

my now (nearly) working code is:

class _Tag(object):
def __init__(self, name, flags=None, **props):
[...]

class _ContainerTag(_Tag):
def __init__(self, name, contents=None, flags=None, **props):
super(_ContainerTag, self).__init__(name=name, flags=flags, **props)
self._contents = coalesce(contents, [])
_module_name = sys.modules[__name__]

class_dic = {}
class_dic['Br'] = _Tag
class_dic['Hr'] = _Tag
class_dic['Html'] = _ContainerTag
class_dic['Table'] = _ContainerTag

for class_name, class_base in class_dic.items():
class TmpClass(class_base):
def __init__(self, **props):
name = class_name.lower()
#super(TmpClass, self).__init__(name=name, **props)
class_base.__init__(self, name=name, **props)
setattr(_module_name, class_name, TmpClass)

br = Br()
print br
table = Table()
print table

br is printed OK, but for table, I get:
AttributeError: 'TmpClass' object has no attribute '_contents'
so, it seems that __init__ of _Tag is not called.
If I try to do the commented line
super(TmpClass, self).__init__(name=name, **props)
instead of
class_base.__init__(self, name=name, **props)
I get:
TypeError: super(type, obj): obj must be an instance or subtype of
type
for print table, print br ist processed OK.
Thanks for help and your perfekt examples,
AXEL.

Jul 18 '05 #5

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

Similar topics

0
by: oliver at gmx | last post by:
Hello, I've installed PHP4.3.4 as ISAPI modul of IIS on WIN2003 Server. I use different php scripts for building my HTML-output. In some php scripts I have to access local files for logging...
4
by: Red | last post by:
I have an array which is dynamically generated by parsing a web page: titles Array ( => bookmarks => New Folder => New Folder2 ) and I want to insert html links into another,...
2
by: Tony Johansson | last post by:
Hello Experts! In C++ how is the term modul defined. An object is a modul but is a class also a modul. Many thanks //Tony
3
by: Jeremy Sanders | last post by:
Hi - I'm trying to subclass a dict which is used as the globals environment of an eval expression. For instance: class Foo(dict): def __init__(self): self.update(globals()) self = 42
2
by: spooky | last post by:
Hey, There is a nice modul called "BtK" at http://home.student.utwente.nl/g.v.berg/btk/ Has someone a link for btk-python on windows? Thx,
7
by: Manuel Bleichner | last post by:
Hello list, I have searched for some time now, but no result... I'm having the following problem: In a module I have a huge number of classes of the form: class A(object): connected_to = ...
0
by: johannaostertag | last post by:
I would like to draw your attention to the following open position at the Department of New Media Technology of MODUL University Vienna (under accreditation): * Geospatial, Semantic and Web 2.0...
3
by: juro | last post by:
Hi, I have a small problem: I'd like to call static variables from different classes - their names are stored in an array. Example of a class: class MyClass1{ public static $mysql_table =...
4
by: chris.lyon | last post by:
I'm trying to generate visual python objects from django objects and therefore have objects called 'Ring' and 'Cylinder' as django objects and I want to create objects of those names in visual. I...
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
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)...
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...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
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
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.