10
$\begingroup$

Using 2.67b for python scripting I get this: while importing math, numpy on the scripting console, internal variables seem to be fine but when running scripts need to manually define numbers likely to be enabled when importing math, numpy like PI, E, C and several others I think.

Could that be a version problem or do you have to manually define each variables and constants over the scripting editor?

$\endgroup$

1 Answer 1

10
$\begingroup$

The python console has various convenience imports, from math import * being one of them.

Text from the console:

PYTHON INTERACTIVE CONSOLE 3.3.2 (default, May 21 2013, 15:40:45)  [GCC 4.8.0 20130502 (prerelease)]

Command History:     Up/Down Arrow
Cursor:              Left/Right Home/End
Remove:              Backspace/Delete
Execute:             Enter
Autocomplete:        Ctrl-Space
Zoom:                Ctrl +/-, Ctrl-Wheel
Builtin Modules:     bpy, bpy.data, bpy.ops, bpy.props, bpy.types, bpy.context, bpy.utils, bgl, blf, mathutils
Convenience Imports: from mathutils import *; from math import *
Convenience Variables: C = bpy.context, D = bpy.data

>>> pi
3.141592653589793

Importing the entirety of a module using * when not experimenting in the console is generally seen as bad practice / not pythonic, and explained in part here.

Remember, you can never know for sure what names a module exports, so either take what you need — from module import name1, name2, or keep them in the module and access on a per-need basis

For scripting outside of the console use explicit imports. Create a template with all your frequently used imports, similar to this, and place it in the ../scripts/templates_py/ folder:

import bpy
import mathutils
from mathutils import Vector, Matrix
from math import pi, sin, cos, tan

this article goes into great detail about code structure and includes a short section on imports, definitely food for thought if the topic isn't well understood.

$\endgroup$
1
  • 2
    $\begingroup$ the alternative would be import math and then access math.pi, math.sin etc. For maths this would be overkill, but for more complex modules you should consider that. It also becomes important if you use both math and cmath. And it's noteworthy that you can do things like from math import sin as sine in order to give you more freedom with your own variables' names $\endgroup$ Commented Jul 19, 2013 at 9:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .