473,782 Members | 2,505 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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\tin it(self, name='%s')\n\t\ tsuper(%s,
self).__init(na me=name)\n"%dic t(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 1477
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\tin it(self, name='%s')\n\t\ tsuper(%s,
self).__init(na me=name)\n"%dic t(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__(s elf, 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__(s elf, 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(_Containe rTag, self).__init__( name=name, flags=flags, **props)
self._contents = coalesce(conten ts, [])
_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.lowe r()
#super(TmpClass , self).__init__( name=name, **props)
class_base.__in it__(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.__in it__(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
1507
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 purposes. Now my question: What rights does a php script have on the server. If a user requests a php-script - which user account does this "request-thread" have? I know from the Apache WebServer on Linux that I can specify the user or group of a...
4
1810
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, nultidemensional array which is based on the first array: $dl]]]=$link;
2
2188
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
2694
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
1371
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
4915
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 = <other attributes...>
0
1293
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 Technologies http://www.ecoresearch.net/download/nmt-tech.pdf MODUL University Vienna is a recently founded private university on top of Kahlenberg, a scenic hill overlooking Vienna. The university combines
3
1534
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 = "table1"; } Now I would like to do something like this: $classes=array("MyClass1","MyClass2","MyClass3"); foreach ($classes as $item)
4
1286
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 can cludge it in varius ways by using dir and lots of if lookups but is there a way of doing this that allows the name to generate a visual object of the appropriate name or fail nicely if the visual object doesn't exist?
0
9639
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10146
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
10080
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,...
0
9942
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5378
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5509
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4043
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
2
3639
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2874
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.