How Do You Include Header Files in Python?

  • Context: Python 
  • Thread starter Thread starter cpscdave
  • Start date Start date
  • Tags Tags
    Block Code Python
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
4 replies · 3K views
cpscdave
Messages
402
Reaction score
120
In c I quite often build header files with a bunch of predefined data. Fill it with structures or what not.
Then to include that information in my program its a simple #include "myHeader.h"

Is there a way I can do this in python?
I've created another file "myHeader.py"
Have put in some code to setup these values
then in main file I put import myHeader but it doesn't appear to work as I intend.

Any suggestions??*edit* I figured I can do it by doing
from myHeader import *

SOLVED :) unless there is a more proper way to accomplish this in python :)
 
Physics news on Phys.org
Yes you found the python way of doing it. Python doesn't have any macro features like C and hence no need to pull in a file that way like C.
 
  • Like
Likes   Reactions: cpscdave
Better would be to

import myHeader as mh

then refer to the objects created in myHeader as mh.foo, mh.baz, etc. Or at least limit the names that gets pulled into your namespace using "*" by adding a line at the end of myHeader.py:

__all__ = ['foo', 'bar', 'baz']
 
cpscdave said:
In c I quite often build header files with a bunch of predefined data. Fill it with structures or what not.
Then to include that information in my program its a simple #include "myHeader.h"
Is there a way I can do this in python?

Data only? Use JSON.

https://docs.python.org/3.4/library/json.html

edit: Ops, didn't see you were doign import *. it's a really bad idea. It imports every symbol from your module into the global namespace, which means there is a 'danger' of a collision. One day you'll add a new data field and the program will develop an error because you re-used a name. With Python, it might not crash and instead just generate subtly incorrect output. Better to specifically import what you need: 'from <x> import <y>' or put everything into a class, and import that one class instead.
 
Last edited: