[Tutor] does python have something like "#include" in C?

Kent Johnson kent37 at tds.net
Mon Jun 29 20:47:40 CEST 2009


On Mon, Jun 29, 2009 at 1:23 PM, Robert Lummis<robert.lummis at gmail.com> wrote:
> Here's an example that seems not possible in python. I'm probably
> missing something so please enlighten me. I only tried doing this as
> an exercise to show myself how name references work. I'm not saying
> it's needed or that it's good practice.
>
> I can write the following as a single file and it works as expected:
>
> ===snip===
> #!/usr/bin/python
>
> def show(*args):
>    print
>    for arg in args:
>            print arg + ':',
>            exec('print ' + arg)
>
> a=15
> b='hello'
> x=['bob',3]
>
> show('a')
> show('a','b')
> show('a','b','x')
> ===snip===
>
> The calls to 'show' output lines like "a: 15" which could be useful
> for debugging or some such purpose.
>
> However, it seems that I can't put the function definition in a file
> and import it because I can't find a way to refer to an object in the
> main program file from within a module file.

Right. We did recently discuss ways to implement this function:
http://www.mail-archive.com/tutor@python.org/msg35873.html

> I understand that it's a
> good thing to contol which namespaces are referenced by which code but
> isn't there sometimes a need for code in a module to access the main
> program file's namespace? My example may be a little contrived but
> isn't this ability legitimately needed at times?

Generally no, that would be a design smell. Module dependencies should
be one-way; if main needs module foo, then foo should not have to know
about main.

Kent


More information about the Tutor mailing list