473,396 Members | 1,767 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.

simulating #include in python

We are currently investigating whether to move the data files from our
application into python for ease of maintenance. Each data item turns
into a class definition with some class data. The python approach
looks great, but there is one feature that we'd like to have.

Currently the data files can include other data files. Typically
thats used to import standard definitions from somewhere else (rather
like #include in C - conceptually its a completely textual import).
We use them something like this

include("../../standard_definitions")
include("../shared_definitions")

class A(base_from_standard_definitions): pass
class B(A): pass

include("more_definitions")

The includes act much more like #include than import - all the symbols
from the file before the include() must be available to the included
file and the included file must export all its symbols back to the
parent.

These can of course be re-arranged to work in a pythonic way using
'from x import *' and putting "../.." on sys.path instead of the
includes. However there are over 500 of these files so I'd prefer a
more automatic solution which doesn't require re-arrangement in the
interim. (The re-arrangement is needed because "more_definitions"
above might refer to A, B or anything defined in
standard/shared_definitions leading to mutually recursive imports and
all the pain they cause)

I have implemented a working prototype, but it seems such a horrendous
bodge that there must surely be a better way! I'd really like to be
able to run an __import__ in the context of the file thats running the
include() but I haven't figured that out.

Here is the code (avert your eyes if you are of a sensitive nature ;-)
Any suggestions for improvement would be greatly appreciated!

def include(path):

# Add the include directory onto sys.path
native_path = path.replace("/", os.path.sep)
directory, module_name = os.path.split(native_path)
if module_name.endswith(".py"):
module_name = module_name[:-3]
old_sys_path = sys.path
if directory != "":
sys.path.insert(0, directory)

# Introspect to find the parent
# Each record contains a frame object, filename, line number, function
# name, a list of lines of context, and index within the context.
up = inspect.stack()[1]
frame = up[0]
parent_name = frame.f_globals['__name__']
parent = sys.modules[parent_name]

# Poke all the current definitions into __builtin__ so the module
# uses them without having to import them
old_builtin = __builtin__.__dict__.copy()
overridden = {}
poked = []
for name in dir(parent):
if not (name.startswith("__") and name.endswith("__")):
if hasattr(__builtin__, name):
overridden[name] = getattr(__builtin__, name)
else:
poked.append(name)
setattr(__builtin__, name, getattr(parent, name))

# import the code
module = __import__(module_name, parent.__dict__, locals(), [])

# Undo the modifications to __builtin__
for name in poked:
delattr(__builtin__, name)
for name, value in overridden.items():
setattr(__builtin__, name, value)

# check we did it right! Note __builtin__.__dict__ is read only so
# can't be over-written
if old_builtin != __builtin__.__dict__:
raise AssertionError("Failed to restore __builtin__ properly")

# Poke the symbols from the import back in
for name in dir(module):
if not (name.startswith("__") and name.endswith("__")):
setattr(parent, name, getattr(module, name))

# Restore sys.path
sys.path = old_sys_path

--
Nick Craig-Wood <ni**@craig-wood.com> -- http://www.craig-wood.com/nick
Nov 22 '05 #1
2 1477
Nick Craig-Wood wrote:
I'd*really*like*to*be able to run an __import__ in the context of the file
thats running the include() but I haven't figured that out.


execfile()?

Peter
Nov 22 '05 #2
Peter Otten <__*******@web.de> wrote:
Nick Craig-Wood wrote:
I'd*really*like*to*be able to run an __import__ in the context of the file
thats running the include() but I haven't figured that out.


execfile()?


Yes thats exactly what I was looking for - thank you very much!

--
Nick Craig-Wood <ni**@craig-wood.com> -- http://www.craig-wood.com/nick
Nov 22 '05 #3

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

Similar topics

3
by: jimif_fr | last post by:
How is it possible to simulate the keyboard entries (and the mouse events) of one program, from another program. The first program is not written for this purpose and is a not aware of the...
5
by: jimmy | last post by:
I am trying to simulate typedef template similar to the suggestion of Herb Sutter in the following article: http://www.gotw.ca/gotw/079.htm However when implementing typedef templates according...
20
by: Robert | last post by:
Need some help to stop me going around in circles on this one.... Have a nested subform (subform2) which simulates a continuous form for the record on the parent subform. Subform2 has rows of...
1
by: Johannes Zellner | last post by:
Hello, when embedding python: how can I create a type which simulates item getters and setters? Something like this: void setter(PyObject* self, int i, PyObject new_value) { // do something...
4
by: Bill Pursell | last post by:
I've been thinking of doing things like the following: $ cat foo.h struct foo{ int a; void (*init)(struct foo *, int); }; void new_foo(struct foo *self);
5
by: Keo932 | last post by:
Hello all, I am finishing up my program to simulate a tollbooth by using classes. What happens is cars passing by the booth are expected to pay a fifty cent toll. The program keeps track of the...
5
by: Chris Lieb | last post by:
I am trying to create a "pseudo-class" using structs. Member variables seem easy enough to do. However, trying to implement member functions has led to nothing but frustration. I have tried...
15
by: Bjoern Schliessmann | last post by:
Hello all, I'm trying to simulate simple electric logic (asynchronous) circuits. By "simple" I mean that I only want to know if I have "current" or "no current" (it's quite digital) and the only...
9
by: chikkubhai | last post by:
Why is the result different for the following set of two code snippets Code without using this pointer #include <string> #include <iostream> using namespace std; struct X { private:
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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,...
0
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,...
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...

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.