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

Wayne srilyk at gmail.com
Mon Jun 29 19:47:58 CEST 2009


On Mon, Jun 29, 2009 at 12: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.

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?


I can't think of a single legitimate reason the module would need to access
the object in the namespace in any way that isn't already provided.
Especially in python it breaks the model of what objects are.

Strings (and integers AFAIK) are literals. Consider:
>>> x[0] = 'c'
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment

When you create a string in c/c++ you have a string of characters, and you
can edit it as such.
When you say knights = 'who say ni' in python, you are referencing knights
to the literal string 'who say ni'. As far as python is considered, every
single string combination already exists as an object, and your variable
just references that object.

At least that's the way I've understood it. So when you're trying to access
the namespaces name for the object it's useless because there's nothing you
can do with it. (And really it shouldn't be the responsibility of an outside
function to modify the value of a variable anyway! It's also bad from a data
security POV. You don't want functions messing with your data just by
accident)

Anyway... that's as far as I've been taught (and taught myself)... anyone
notices any errors, please correct them!
HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090629/84541623/attachment.htm>


More information about the Tutor mailing list