0

Rather than defining

from numpy import cos as cos
from numpy import arccos as arccos

and so on, can I do something like

trigfunctions = ('cos','arccos','sin','arcsin','tan','arctan')
for method in trigfunctions:
    setattr(HERE,method,getattr(numpy,method))

Where HERE is either global space (or possibly, local function environment)? This would make it easier to define general functions based on cos, arccos without specifying the namespace, and loading the appropriate function from the desired module (e.g., math if numpy is not available). I realize that this can lead to errors when applied very generally, but in some small instances it would be useful.

glglgl
  • 89,107
  • 13
  • 149
  • 217
hatmatrix
  • 42,883
  • 45
  • 137
  • 231

1 Answers1

5

If you mean importing with the same name, simply leave off the as:

from numpy import cos, arccos, sin, arcsin, tan, arctan

Beyond that, you can use globals() to get the symbol table for the current module:

me=globals();
trigfunctions = ('cos','arccos','sin','arcsin','tan','arctan')
for method in trigfunctions:
    me[method] = numpy.__dict__[method]

You can also use sys.modules[__name__] to reference the current module.

Community
  • 1
  • 1
outis
  • 75,655
  • 22
  • 151
  • 221
  • But why `numpy.__dict__[method]` rather than `getattr(numpy,method)`? – hatmatrix Oct 23 '11 at 21:56
  • 1
    No particular reason; it's just another way of doing the same thing a little more directly. Considering the comment regarding [module namespaces](http://docs.python.org/tutorial/classes.html#id2) in the Python docs, `getattr` is probably the better of the two. – outis Oct 23 '11 at 22:35
  • 1
    Thanks for your response -- yes, seems like getattr would be better in this case. – hatmatrix Oct 23 '11 at 23:45