Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Python [Python] include block of code

  1. Apr 9, 2015 #1
    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 :)
  2. jcsd
  3. Apr 9, 2015 #2


    Staff: Mentor

    Yes you found the python way of doing it. Python doesnt have any macro features like C and hence no need to pull in a file that way like C.
  4. Apr 10, 2015 #3
    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']
  5. Apr 10, 2015 #4

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    Or even
    import myHeader

    Using "from myHeader import *" is the moral equivalent of "using namespace std;" in C++.
  6. Apr 30, 2015 #5
    Data only? Use JSON.


    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: Apr 30, 2015
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook