Thoughts about modules

Kirk McDonald kirklin.mcdonald at gmail.com
Thu Jun 29 14:09:47 PDT 2006


Kirk McDonald wrote:
> 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.
> 

Some additional features of Python. :-)

> So, given a module foo.bar with a function inside named baz, we can say:
> 
>  >>> import foo.bar
>  >>> foo.bar.baz()
> 

Like D, you can say e.g.:
 >>> import foo.bar, foo.baz, foo.boo

> 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()
> 

You can also say:
 >>> from foo.bar import baz, boo, blah

Which is quite useful if you just need a handful of names from a module.

> (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()
> 

This can similiarly be expanded as:
 >>> from foo.bar import baz as b, boo as o, blah as a

> 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