How can i use a variable without define it ?

Ben Finney bignose+hates-spam at benfinney.id.au
Wed Jul 16 05:35:35 EDT 2008


zhw <weizhonghua.ati at gmail.com> writes:

> Here is a example that I want to complete:
> >>> import sys, new
> >>> context={"name":"david", "sex":"male"}

Here you have a set of values addressible by name.

> >>> sys.modules["foo"] = new.module("foo")

Why do you believe you need to create a module object?

> >>> import foo
> >>> for attr in context:
> 	setattr(foo, attr, context[attr])

This doesn't appear to get you anything that isn't already available
with the 'context' mapping.

> >>> def bar():
>         # here is a error
>         # import * only allowed at module level
> 	from foo import *
>         print name, sex

You can simply do:

    >>> context = {'name': "david", 'sex': "male"}
    >>> def bar():
    ...     print context['name'], context['sex']
    ...
    >>> bar()
    david male

Or, more flexible and more explicit:

    >>> foo = {'name': "david", 'sex': "male"}
    >>> def bar(context):
    ...     print context['name'], context['sex']
    ...
    >>> bar(foo)
    david male

What problem are you trying to solve?

-- 
 \      “The best mind-altering drug is truth.” —Jane Wagner, via Lily |
  `\                                                            Tomlin |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list