2

My python project path /project and these are its files :

/project/test.py
/project/templates/
/project/includes/
/project/includes/config.py
# config.py
import os
template_path = os.path.join(os.path.dirname(__file__), "templates")

when I used execute() function to include config.py from test.py , the /project/includes/config.php file was executed and the result was returned to /project/includes/test.py so template_path variable was saved as /project/includes/templates/ and templates folder would not be found there .
I want a function to include /project/includes/config.py from /project/test.py and execute all functions in /project/includes/config.py through test.py.

miku
  • 181,842
  • 47
  • 306
  • 310
Basem
  • 443
  • 2
  • 7
  • 15

3 Answers3

3

Create a (empty) file __init__.py in includes.

In test.py, call config.py by doing an import.

from includes import config

So if there is a function say foo in config, you will call it like:

config.foo()

Refer to the documentation (as pointed out by The MYYN)

Community
  • 1
  • 1
user225312
  • 126,773
  • 69
  • 172
  • 181
  • Is this statement "from includes import config" must be at the beginning of file ? – Basem Dec 26 '10 at 13:32
  • 2
    It should be at the beginning but you can have it anywhere you want. But PEP8 (Python style guide) recommends: `Imports are always put at the top of the file, just after any modulecomments and docstrings, and before module globals and constants.` – user225312 Dec 26 '10 at 13:37
3

In Python you don't include, you import, also you don't import files and directories, you import modules and packages, which are often (but not always) files and directories present somewhere in the Python path. Therefore the common practice is to put all your modules in a package which the user should place in the Python path, and then import the modules from there. Importing files is possible but discouraged.

If your config module is a real module part of your library, internal configuration or site configuration, you need to create a new package named as your project is named, put the config and other modules inside it. Also note that because of the module/package structure used in Python, creating a project with an includes directory for the modules inside it isn't going to work very well.

If your config.py file is supposed to be user configuration, you can look at the ConfigParser module, or use the third-party cfgparse.

Rosh Oxymoron
  • 20,355
  • 6
  • 41
  • 43
2

You usually include code from other files (called modules) via import.

miku
  • 181,842
  • 47
  • 306
  • 310