473,396 Members | 2,024 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,396 software developers and data experts.

Import into specified namespace

Hi experts

Is is possible to import/manipulate a module such that
I can supply its __dict__?

I want to supply my own dict subclass object to be filled
by the import, e.g. a class like:
class MyModuleDict(dict): .... def __setitem__(self,name,val):
.... print name, val
.... dict.__setitem__(self,name,val)

__dict__ is a readonly attribute, so I can't change it after
the import, i.e. the following doesn't work:
import sys
mydic = MyModuleDict()
mydic.update(sys.__dict__)
sys.__dict__ = mydic

Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: readonly attribute

I have experimented with new.module(), __import__(),
imp.*, exec/eval/execfile+globals/locals but to no avail.

Is there any way to do this?

Thanks
Fritz
Jul 18 '05 #1
2 1937
Fritz Bosch <ut****@hotmail.com> wrote:
...
__dict__ is a readonly attribute, so I can't change it after
the import, i.e. the following doesn't work:
import sys
mydic = MyModuleDict()
mydic.update(sys.__dict__)
sys.__dict__ = mydic

Traceback (most recent call last):
File "<interactive input>", line 1, in ?
TypeError: readonly attribute


Why not sys.modules['sys'] = mydic instead of trying to rebind
sys.__dict__? You can't affect those other modules which have ALREADY
imported sys, yourself included (but as for you, you can remedy that
easily -- sys = sys.modules['sys'] = mydic...), but otherwise you should
be OK. sys.__dict__.update(mydic) as the last statement might also be
an alternative (and if it works for your purposes, it's cleaner than
rebinding sys.modules['sys']!-).
Alex
Jul 18 '05 #2
al*****@yahoo.com (Alex Martelli) wrote:
...
Why not sys.modules['sys'] = mydic instead of trying to rebind
sys.__dict__? You can't affect those other modules which have ALREADY
imported sys, yourself included (but as for you, you can remedy that
easily -- sys = sys.modules['sys'] = mydic...), but otherwise you should
be OK. sys.__dict__.update(mydic) as the last statement might also be
an alternative (and if it works for your purposes, it's cleaner than
rebinding sys.modules['sys']!-).


Thanks for the hint. I actually want a different behavior for the
namespace, so the second suggestion (though cleaner) won't work for
me. In fact, I had to modify the first to get what I want, namely a
namespace (for a module) with a reverse lookup capability, i.e. given
an object, it returns the object's name (if any) inside the namespace.

I eventually got following to run:

Assume a small module 'mymod.py', for which I need a namespace with
reverse lookup capability:
-------------------------------------------------------------
import sys

def fn():
name = fn.__module__
# print the id of this module in sys.modules, along with the ids
# of the function and current globals, and the module's dict
print 'mymod name:%s id(sys.modules[name]):%s' % (
name, id(sys.modules[name]))
print ' id(fn.func_globals):%s id(globals()):%s \
id(sys.modules[name].__dict__):%s' % (
id(fn.func_globals), id(globals()),
id(sys.modules[name].__dict__))
-------------------------------------------------------------

To do this, I have defined following namespace.py module:
-------------------------------------------------------------
import sys
import os

class RNameSpace(dict):
def __init__(self, *args, **kw):
dict.__init__(self, *args, **kw)
self.__rdict = {}
for name, val in self.items():
self.__rdict[id(val)] = name
def __setitem__(self, name, val):
if name in self:
del self.__rdict[id(self[name])]
dict.__setitem__(self, name, val)
self.__rdict[id(val)] = name
def update(self, other):
for name, val in other.items():
self[name] = val
def __delitem__(self, name):
if name in val:
del self.__rdict[id(self[name])]
dict.__delitem__(self, name)
def rlookup(self, obj):
return self.__rdict[id(obj)]

class Module(object):
def __init__(self, mod_name, namespace=None):
if namespace is None:
namespace = RNameSpace()
if isinstance(namespace, RNameSpace):
self.__dict__ = namespace
else:
self.__dict__ = RNameSpace(namespace)
module = __import__(mod_name)
self.__dict__.update(module.__dict__)
def reload(self):
file = os.path.splitext(self.__file__)[0] + '.py'
execfile(file, self.__dict__)
def install(self):
mod_name = self.__name__
sys.modules[mod_name] = self

if __name__ == '__main__':
ns = RNameSpace(a=1,b=2)
c1 = 3
ns['c']=c1
a1 = ns['a']
print ns.rlookup(a1), ns.rlookup(c1)

print "create Module md from 'mymod' to use RNameSpace:"
md = Module('mymod')
print 'id(md):%s id(md.__dict__):%s' % (id(md), id(md.__dict__))

print "\nnote that md.fn still uses original namespace:"
md.fn()

print '\nreload the file - now md.fn used the RNameSpace:'
md.reload()
md.fn()

print '\nan import still uses the original namespace:'
import mymod
mymod.fn()

print '\ninstall the module - subsequent imports \
use the altered namespace:'
md.install()
import mymod
mymod.fn()
-------------------------------------------------------------

From the above it can be seen that it was necessary to create a
module-like object with the specified namespace and to call execfile
with this namespace ? I could find no other way to make the
classes/functions inside mymod use the namespace. Replacing the
sys.modules entry with this object then causes subsequent imports to
use the module-like object.

B.t.w. am I re-inventing the wheel here? Is there another way to get
the name from given an object id?

Fritz
Jul 18 '05 #3

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

Similar topics

2
by: Charles Fineman | last post by:
I've been asked to look over an integration toolkit that has a bunch of schemas to specify message format. There are a couple of strange things I noticed right off the bat and I wanted to get...
4
by: Iain A. Mcleod | last post by:
Hi I'm stuck with the following schema validation problem in VS.NET 2003: I have two types of xml document and related schema: project and projectCollection. A projectcollection is just a set...
2
by: darrel | last post by:
I've built a control. At the top of my control, I have this: Imports Microsoft.VisualBasic Then, later, I call a function like this: DateTime.Now.Year.ToString() This works fine on my...
4
by: Bruce W. Roeser | last post by:
All, I'm reading a book by Charles Petzold (Programming VS.Net). Pretty good content but am confused about the difference. From the text: ...
2
by: Carmit | last post by:
Hi, I'm trying to build a proxy for this webservice: http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/EndTransactionLLSRQ.wsdl I'm getting the following error: Error: Unable to import...
23
by: Shane Hathaway | last post by:
Here's a heretical idea. I'd like a way to import modules at the point where I need the functionality, rather than remember to import ahead of time. This might eliminate a step in my coding...
3
by: Chris | last post by:
Hi, 1) In file test.aspx, i put: <%@ Page Language="VB" AutoEventWireup="false" CodeFile="test.aspx.vb" Inherits="test" %> <%@ import namespace="System.Data"%> <%@ import...
49
by: Martin Unsal | last post by:
I'm using Python for what is becoming a sizeable project and I'm already running into problems organizing code and importing packages. I feel like the Python package system, in particular the...
2
by: Grant Robertson | last post by:
I am having a little trouble sorting out the exact differences between using wildcards and using import in XML schema. I know that a wildcard allows any global elements from the referenced...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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...
0
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...
0
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...
0
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
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...

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.