Thoughts about modules
Kirk McDonald
kirklin.mcdonald at gmail.com
Thu Jun 29 13:58:39 PDT 2006
Sjoerd van Leent wrote:
> The thing I'd see useful here would be:
>
> import fb : foo.bar;
>
> Indicates all methods from module "foo.bar" are in local namespace "fb"
>
> import $ : foo.bar;
>
> Would be the same as
>
> import foo.bar : foo.bar;
>
> Regards,
> Sjoerd
It is worth reviewing the Python syntax for imports here, I think.
Python uses the FQN import by default, but supports importing
unqualified names as well.
So, given a module foo.bar with a function inside named baz, we can say:
>>> import foo.bar
>>> foo.bar.baz()
To import a module and make it available as an alias, you'd say:
>>> import foo.bar as fb
>>> fb.baz()
To only import a specific name from a module, you'd say:
>>> from foo.bar import baz
>>> baz()
(This is a feature I'd love to see in D, actually. The ability to only
import a specific name from a module would be great.)
To import a specific name under an alias, you'd say:
>>> from foo.bar import baz as b
>>> b() # calls foo.bar.baz()
If you want to import all names from a module into the current namespace
(the D style of import), you can say:
>>> from foo.bar import *
>>> baz()
It's worth noting that, for all of these except the last form, all names
that are imported are explicitly mentioned in the import statement. I
think this is a highly desirable state of affairs. It is for this reason
that frivolous use of the "from x import *" form is somewhat frowned
upon. It is quite useful for importing some large libraries, however
(certain GUI libraries, for instance), so there are certainly valid uses
for it.
The visibility of imported names, then, follows naturally:
# blah.py
from foo.bar import baz
# EOF
>>> import blah
>>> blah.baz() # calls foo.bar.baz
>>> from blah import baz
>>> baz() # calls foo.bar.baz
-Kirk McDonald
More information about the Digitalmars-d
mailing list