There are several questions related to reading python code from external files, including
Python: How to import other Python files
How to include external Python code to use in other files?
But it's not clear how to include snippets of text from an external file, as is standard practice with the CPP #include
directive. For example, the following code:
def get_schema():
schema1 = \
{
"$schema": "http://json-schema.org/draft-04/schema#",
"id": "0",
"type": "object",
"properties": {
"i": { "type": "integer" },
"n": { "type": "string" }
}
}
return(schema1)
s = get_schema()
print(s)
returns the expected dict:
{'id': '0', '$schema': 'http://json-schema.org/draft-04/schema#', 'type': 'object', 'properties': {'i': {'type': 'integer'}, 'n': {'type': 'string'}}}
But what I want to do is write the code so that it imports variable definitions from external files that do not include any python code (function definitions or variable assignments):
def get_schema():
schema1 = \
#include "schema1.json"
return(schema1)
s = get_schema()
print(s)
I'm sure this could be done with a bunch of code to open the definition files, read the contents into a string, add pre- and post-amble lines of python, and then exec the string, but it seems that there should be a simpler way to just include text in a function definition. Is there?