问题
First I do know about 'import'. When I try 'import' it doesn't work. What I'm trying to do is split a single module into two parts, one of which is editable by a group and the other of which is not. I want the group to write well-defined 'retrieval functions' without the temptation or ability to edit the backend code that runs them (even accidentally). The changes in namespace on an 'import' are getting in my way. I'm looking for a macro-style inclusion of File_A's text within File_B, to be run inline as if it were part of File_B.
This is what I'm doing:
I have some generalized code that is designed to call a list of information retrieval functions in turn, and store the info in a unified way. To do this I add its text name to a list:
DataTypes = ['TypeA','TypeB','TypeC']
... and then define a function that knows how to get each type, and returns a populated object class:
def Get_TypeA:
# do some stuff to retrieve info
InfoObj Data
# Populate Data with the info I got
return Data
def Get_TypeB:
# etc. etc.
return Data
def Get_TypeC:
# etc. etc.
return Data
# Backend code below this line, hopefully nobody touches it?
# (But really it would be best if this was in a different file
# that is harder to mess with and has locked-down permissions.)
class InfoObj:
# stuff stuff definitions methods etc.
These functions will be edited by people with only a basic knowledge of Python but often bad coding habits, but who need to be able to frequently customize what is gathered and displayed. I already have a backend that checks the list and calls the functions, but I just want to move those definitions into a separate file from the rest of the backend code, but work as if they were right there inline. (i.e. turn the "hopefully nobody touches it" into a "people have to go out of their way to touch it")
Does Python have this?
When I try using Import, the retrieval functions lose contact with the definition of InfoObj. This happens whether I use 'import otherFile' or 'from otherFile import *'.
EDIT: This is what I'm using to retrieve the various types in a standard way:
THISMODULE = sys.modules[__name__]
for type in DataTypes:
RetrievalFn = getattr( THISMODULE, 'Get_'+type )
Data = RetrievalFn()
StoreInDB(Data)
(though this is boiled down to basics, there are try/except clauses, validation steps to make sure Data was populated correctly and doesn't contain incorrect types or bad stuff, and code to notify the team if and where something breaks but still process the rest of the items. The goal is that someone making edits does not break the rest of the checks, even if their edits broke one of the checks.)
回答1:
This can be done with execfile(), but you should consider using some other mechanism for this instead such as polymorphism or plugins.
来源:https://stackoverflow.com/questions/6348166/in-python-how-can-i-include-not-import-one-file-within-another-file-macro-st