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

Build classes/packages dinamicaly

Hi,
I have a package that generates classes from a
set of XML files using exec.

So far the classes appear in the global namespace.

Is there any way to also create packages dinamicaly
and add the classes to those packages?

Thanks in advance,
Paulo Pinto

Jul 18 '05 #1
7 1186
Paulo Pinto wrote:
I have a package that generates classes from a
set of XML files using exec.

So far the classes appear in the global namespace.

Is there any way to also create packages dinamicaly
and add the classes to those packages?

Thanks in advance,
Paulo Pinto

import types
mymodule = types.ModuleType("mymodule")
exec "def demo():\n\tprint 'hello from', __name__\n" in mymodule.__dict__ mymodule.demo() hello from mymodule


Seems to work. I haven't used it myself, though.

Peter

Jul 18 '05 #2
Paulo Pinto <pa*********@cern.ch> wrote in message news:<br**********@sunnews.cern.ch>...
Hi,
I have a package that generates classes from a
set of XML files using exec.

So far the classes appear in the global namespace.

Is there any way to also create packages dinamicaly
and add the classes to those packages?

Thanks in advance,
Paulo Pinto


By packages I think you mean modules. Here is a solution in Python 2.3:
from types import ModuleType
mymodule=ModuleType("mymodule")
print mymodule <module 'mymodule' (built-in)> class C(object): pass .... mymodule.C=C


In older Python versions, look for the module "new".
Jul 18 '05 #3
Thanks it is want I was looking for.
However I still have a problem.

I want to make the module available to the
caller as if he did an import.

For example, if I make the following call

some_module.generate_module('dummy')

Where some_module is the module that generates
modules dinamicaly, and dummy is the name of the
new module.

I would like to be able to do

dummy.something()

after that call.

I've discovered that if I do something like this

globals()['dummy'] = module_instance_returned_by_new.module()
It works, but it must be done at the same level I want to
call dummy.something() and not from inside some_module. Because
if I do it inside the module, globals() will be refering to the
module globals and not to parent scope.

Basically I would like to import the generated module to the
module that is invoking generate_module() like an uplevel in
Tcl.

Is this possible?

Cheers,
Paulo Pinto

Peter Otten wrote:
Paulo Pinto wrote:

I have a package that generates classes from a
set of XML files using exec.

So far the classes appear in the global namespace.

Is there any way to also create packages dinamicaly
and add the classes to those packages?

Thanks in advance,
Paulo Pinto


import types
mymodule = types.ModuleType("mymodule")
exec "def demo():\n\tprint 'hello from', __name__\n" in
mymodule.__dict__
mymodule.demo()


hello from mymodule
Seems to work. I haven't used it myself, though.

Peter


Jul 18 '05 #4
Paulo Pinto wrote:
Thanks it is want I was looking for.
However I still have a problem.

I want to make the module available to the
caller as if he did an import.

For example, if I make the following call

some_module.generate_module('dummy')

Where some_module is the module that generates
modules dinamicaly, and dummy is the name of the
new module.

I would like to be able to do

dummy.something()

after that call.

I've discovered that if I do something like this

globals()['dummy'] = module_instance_returned_by_new.module()
It works, but it must be done at the same level I want to
call dummy.something() and not from inside some_module. Because
if I do it inside the module, globals() will be refering to the
module globals and not to parent scope.

Basically I would like to import the generated module to the
module that is invoking generate_module() like an uplevel in
Tcl.

Is this possible?


Don't know, but rebinding in the calling scope from inside a function call
looks like fighting the language to me. Maybe redefining __import__() would
be better:

<myimport.py>
import __builtin__
import types, sys

originalimport = __builtin__.__import__

def myimport(name, *args):
print "importing", name
try:
return originalimport(name, *args)
except ImportError:
print "generating", name
module = types.ModuleType(name)
exec "def demo(*args):\n\tprint 'demo%r' % (args,)\n" in
module.__dict__
sys.modules[name] = module # put it into the cache
return module

__builtin__.__import__ = myimport
</myimport.py>

I simply generate any module that cannot successfully be imported, but you
could change this to meet your needs. Now a usage example:

<usemyimport.py>
import myimport # put it first, because it messes with the built-ins

print "first import"
import os
import generated
print
print "second import"
import os, generated

generated.demo("hi", "there")
</usemyimport.py>

However, this is just a smoother variant of the

module = generate("modulename")

pattern.

Peter
Jul 18 '05 #5

"Paulo Pinto" <pa*********@cern.ch> schrieb im Newsbeitrag
news:br**********@sunnews.cern.ch...
| Thanks it is want I was looking for.
| However I still have a problem.
|
| I want to make the module available to the
| caller as if he did an import.
|
| For example, if I make the following call
|
| some_module.generate_module('dummy')
|
| Where some_module is the module that generates
| modules dinamicaly, and dummy is the name of the
| new module.
|
| I would like to be able to do
|
| dummy.something()
|
| after that call.
|
| I've discovered that if I do something like this
|
| globals()['dummy'] = module_instance_returned_by_new.module()
|
|
| It works, but it must be done at the same level I want to
| call dummy.something() and not from inside some_module. Because
| if I do it inside the module, globals() will be refering to the
| module globals and not to parent scope.
|
| Basically I would like to import the generated module to the
| module that is invoking generate_module() like an uplevel in
| Tcl.
|
| Is this possible?

Sure

Put this in a file called "dynmods.py" or something:

from types import ModuleType
def generate_module(dynmod):

exec '%(dynmod)s = ModuleType("%(dynmod)s")' % vars() in globals()
dynmod = globals()[dynmod]
exec "def something():\n\tprint 'hello from', __name__\n" in
dynmod.__dict__
return dynmod

fire up a shell and:
import dynmods
dummy = dynmods.generate_module("dummy")
print dummy <module 'dummy' (built-in)> dummy.something() hello from dummy


Is this what you were looking for?

Regards

Vincent Wehren
|
| Cheers,
| Paulo Pinto
|
| Peter Otten wrote:
| > Paulo Pinto wrote:
| >
| >
| >>I have a package that generates classes from a
| >>set of XML files using exec.
| >>
| >>So far the classes appear in the global namespace.
| >>
| >>Is there any way to also create packages dinamicaly
| >>and add the classes to those packages?
| >>
| >>Thanks in advance,
| >>Paulo Pinto
| >
| >
| >>>>import types
| >>>>mymodule = types.ModuleType("mymodule")
| >>>>exec "def demo():\n\tprint 'hello from', __name__\n" in
| >
| > mymodule.__dict__
| >
| >>>>mymodule.demo()
| >
| > hello from mymodule
| >
| >
| > Seems to work. I haven't used it myself, though.
| >
| > Peter
| >
|
Jul 18 '05 #6
> I want to make the module available to the
caller as if he did an import.

For example, if I make the following call

some_module.generate_module('dummy')

Where some_module is the module that generates
modules dinamicaly, and dummy is the name of the
new module.

I would like to be able to do

dummy.something()

after that call.


Well, this isn't the perfect solution, but you can create modules in
the system at runtime like so:

In your code:
mymodule = generate_module() #As above
import sys
sys.modules['dummy'] = mymodule
Now, the user can just do the following: import dummy
dummy.something()


It's not _quite_ what you want, since it doesn't automatically include
it, but it's pretty easy to do. Furthermore, if you standardize the
name of the module, you can just have the user import that by default,
and then use whatever dynamic content you've put inside.

Also, note that mymodule can actually be anything, although you should
still use a value that responds to __getattr__ (anything else would be
really confusing, and probably a Bad Thing).

I hope this helps.

- Brian Chin
Jul 18 '05 #7
Thanks for the replies.
I have now a working solution.

Jul 18 '05 #8

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

Similar topics

17
by: Phil Powell | last post by:
Where can I find an online PHP form validator script library to use? I have tried hacking the one here at work for weeks now and it's getting more and more impossible to customize, especially now...
18
by: vrillusions | last post by:
I've been using functions since I first started using php, but I've been hearing more and more about classes, which I never really looked at that much. I understand the whole OO programming...
9
by: Divick | last post by:
Hi all, does any one know what is the right way to forward declare classes within namespaces. Though I have been using the syntax as follows but it doesn't sound good to me. namespace...
2
by: loren.davie | last post by:
Hi, I'm attempting to build a small app that uses pythoncard for a gui layer. The intention is to use py2app to construct an .app bundle for the Mac. I'm running OS 10.4 on an Intel MacBook...
3
by: hussainbabu | last post by:
creation ,compilation and running of classes developed using packages sample code with clear explanation will help me .
2
by: John Nagle | last post by:
Trying to build M2Crypto on a dedicated server running Red Hat Fedora Core 6. I'm trying to do this right, without manual patching. The error message I'm getting during build is: python...
17
by: Harry George | last post by:
....at least around here. I run a corporate Open Source Software Toolkit, which makes hundreds of libraries and apps available to thousands of technical employees. The rules are that a) a very...
7
by: John Nagle | last post by:
Back in March, I posted this: That was for M2Crypto 0.17. It's still broken in M2Crypto 0.18. And there's no RPM or Windows binary. Nobody actually uses this stuff, do they?
7
by: ne0lithic | last post by:
Dear all, I'm developing a servlet to handle file upload requests. Despite importing all required classes in the build path, I still receive the 'classNotFoundException' for FileItemFactory. 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...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
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: 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.