473,657 Members | 2,418 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sys.modules and __main__ obscureness

Hello all,

I am messing with namespaces, so that code I exec thinks it is
executing in the __main__ module.

I have the following code :

import imp
import sys

# can't call the module '__main__' or 'new_module' returns the real one
module = imp.new_module( '_')
namespace = module.__dict__
namespace['__name__'] = '__main__'

# next put things into the names
# e.g. :
namespace['variable'] = 3

sys.modules['__main__'] = module

print module
print namespace
import __main__
print __main__.__dict __['variable']

This code behaves differently when entered into an interactive
interpreter session. When run as a program you will see that module and
namespace have both become None !!

However the code works, but to get access to the namespace again I have
to import __main__. I just wondered why ?
All the best,
Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

Jul 16 '06 #1
3 2345
Fuzzyman wrote:
This code behaves differently when entered into an interactive
interpreter session. When run as a program you will see that module and
namespace have both become None !!
Thats because the reference count to the current '__main__' module goes
to 0, and the module object gets deleted along with its globals 'module'
and 'namespace'. The code keeps working because the codeobject is
retained by the interpreter.

To make it work, simply retain a reference to the existing module,
before overwriting with the new module.

sys.blahblah = sys.modules['__main__']
sys.modules['__main__'] = module

[sreeram;]
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2.2 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFEuo1Mrgn 0plK5qqURArxlAK CY/AnOz2W0hg408wJ6 q4PhbtvoPwCePbT n
EC3vRrcBbaYtSfN doZy3wVg=
=bzrH
-----END PGP SIGNATURE-----

Jul 16 '06 #2

K.S.Sreeram wrote:
Fuzzyman wrote:
This code behaves differently when entered into an interactive
interpreter session. When run as a program you will see that module and
namespace have both become None !!

Thats because the reference count to the current '__main__' module goes
to 0, and the module object gets deleted along with its globals 'module'
and 'namespace'. The code keeps working because the codeobject is
retained by the interpreter.

To make it work, simply retain a reference to the existing module,
before overwriting with the new module.

sys.blahblah = sys.modules['__main__']
sys.modules['__main__'] = module

[sreeram;]
That was a quick response. :-)

Thanks very much.

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml
>

--------------enigF3B976014D1 66081569F1C89
Content-Type: application/pgp-signature
Content-Disposition: inline;
filename="signa ture.asc"
Content-Description: OpenPGP digital signature
X-Google-AttachSize: 253
Jul 16 '06 #3
Fuzzyman wrote:
That was a quick response. :-)

Thanks very much.
Sigh.. When I'm drowning in arcane win32 c++ crap, I tend to jump on
anything interesting on python-list. It feels like a breath of fresh air!

[sreeram;]
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2.2 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFEuqUIrgn 0plK5qqURAnoTAJ 9aulkTgHFZZZbYb svyKelcLP4C3wCd GwUS
WezD9nYW6AsoU/8ZPTU0SDA=
=1r+I
-----END PGP SIGNATURE-----

Jul 16 '06 #4

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

Similar topics

1
1627
by: KN | last post by:
Hello, I'm new to this list, and I have an important question at the beginning. There is a matter that concerns me - it's the globales implementation. I've read nearly everything I found about this and about problems people were having with using it. And now I'd like to ask here, because it seems to be more than globales() matter, but an object-programming
0
1947
by: Nick Coghlan | last post by:
Anyone playing with the CPython interpreter's new command line switch might have noticed that it only works with top-level modules (i.e. scripts that are directly on sys.path). If the script is inside a package, the invocation will fail with a "Module not found" error. This PEP is aimed at fixing that :) Cheers, Nick.
15
2587
by: Nick Coghlan | last post by:
Python 2.4's -m command line switch only works for modules directly on sys.path. Trying to use it with modules inside packages will fail with a "Module not found" error. This PEP aims to fix that for Python 2.5. Previously, posting of a draft version of the PEP to python-dev and python-list didn't actually generate any responses. I'm not sure if that's an indication that people don't see the restriction to top-level modules as a problem...
9
5348
by: Martin Drautzburg | last post by:
My wxPython program starts execution in mainFrame.py like this class MainApp(wxApp): def OnInit(self): self.mainFrame = MainFrame(None) self.mainFrame.Show() self.SetTopWindow(self.mainFrame) return True
2
1288
by: PGMoscatt | last post by:
Does Python allow a 'global' variable that can be used between different modules used within an app ? Pete
2
2800
by: Tian | last post by:
I am python beginner, I have a question about the interdependence of modules. For example, when I have two modules: module1.py ------------- def plus(x): return add(x,1)
12
2382
by: qwweeeit | last post by:
The pythonic way of programming requires, as far as I know, to spread a big application in plenty of more manageable scripts, using import or from ... import to connect the various modules. In some cases there is a further complication: module importing through an indirect mechanism, like: exec "from " + xxx + " import *". A part the fact that I have not understood the "real" difference between import and from ... import (or also from......
7
2069
by: Jorgen Grahn | last post by:
I have a set of tests in different modules: test_foo.py, test_bar.py and so on. All of these use the simplest possible internal layout: a number of classes containing test*() methods, and the good old lines at the end: if __name__ == "__main__": unittest.main() This is great, because each of the modules are runnable, and I can select classes or tests to run on the commandline if I want to. However, running all the tests from e.g. a...
3
1328
by: ttsiodras | last post by:
With a.py containing this: ========== a.py =========== #!/usr/bin/env python import b g = 0 def main(): global g
0
8402
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
8315
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
8734
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
8508
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
8608
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
7341
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5633
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4164
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...
2
1962
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.