473,714 Members | 2,365 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(di ct): .... def __setitem__(sel f,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(sy s.__dict__)
sys.__dict__ = mydic

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

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

Is there any way to do this?

Thanks
Fritz
Jul 18 '05 #1
2 1955
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(sy s.__dict__)
sys.__dict__ = mydic

Traceback (most recent call last):
File "<interacti ve 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__.up date(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.c om (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__.up date(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_glob als):%s id(globals()):% s \
id(sys.modules[name].__dict__):%s' % (
id(fn.func_glob als), 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__(s elf, *args, **kw)
self.__rdict = {}
for name, val in self.items():
self.__rdict[id(val)] = name
def __setitem__(sel f, 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__(sel f, 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(name space, RNameSpace):
self.__dict__ = namespace
else:
self.__dict__ = RNameSpace(name space)
module = __import__(mod_ name)
self.__dict__.u pdate(module.__ dict__)
def reload(self):
file = os.path.splitex t(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
10025
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 others' thoughts on it (disclaimer, obviously I'm no XML expert so forgive me if these are basic). --------Exhibit A: The start of a response message schema----------- <xsd:schema targetNamespace="http://www.QQQ.com"
4
2502
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 of projects. Therefore, I wish to include the project customType in the projectCollection namespace. I therefore have declared two xsd documents: project.xsd and projectcollection.xsd
2
4242
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 machine. My coworker takes the exact same file, compiles it, and gets errors until he explicitly writes out the function as:
4
6107
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: ---------------------------------------------------------------------------------------------------------------------------------------------------------- The @ Import Directive Next to @ Page, the directive that ASP.NET programmers use the most is @ Import. The @ Import directive is ASP.NET's...
2
22532
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 binding 'EndTransactionSoapBinding' from namespace 'http s://webservices.sabre.com/websvc'.
23
6413
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 process. Currently, my process is I change code and later scan my changes to make matching changes to the import statements. The scan step is error prone and time consuming. By importing inline, I'd be able to change code without the extra scan...
3
2300
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 namespace="System.Data.OleDb"%> .... In file test.aspx.vb, i put:
49
3930
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 isomorphism between filesystem and namespace, doesn't seem very well suited for big projects. However, I might not really understand the Pythonic way. I'm not sure if I have a specific question here, just a general plea for advice. 1) Namespace....
2
1597
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 schema/namespace to be used in an XML instance document based on the current schema but only within the element where the wildcard is specified. When I import a schema, does that allow ANY elements from the imported schema to be used ANYWHERE in the...
0
8712
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9316
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9177
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
9077
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
9021
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
4465
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
4727
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2524
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2113
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.