1

Background:

I'm writing a symbolic package aimed at pypy for representing expressions and taking derivatives. Not working on simplification or anything like that at the moment, just differentiation and evaluation.

Question:

I'm writing expression classes to represent many of the functions in math (sqrt, log, exp, sin, cos, etc, etc). I have named the module that this goes in math to coincide with the module where you natural find said function. I may in the future do the same with cmath and any other module of particular mathematical interest. My module is part of a larger package ldb.algebra so the name math isn't going to collide with anything at the base namespace. However, in order to evaluate expressions I'm going to need to import the system math module inside the ldb.algebra.math module, and I can't do this from inside my math module (or any other module at the same level of package for that matter). Here's my basic path so far:

ldb/
    __init__.py - empty
    algebra/
        __init__.py - empty
        math.py

Contents of ldb/algebra/math.py as an example of the problem:

import math

my_sin = math.sin

Obviously not terribly useful but it shows the idea. I'm using python2 (or rather pypy for python2). I've found that I can get around this by creating a subpackage, a module under that say sys_math, importing math in that module and exposing the necessary functions but this seems like a lot of work and an ugly mess.

So my question is: can I get at the system math module while still having a module called ldb.algebra.math? Perhaps something funny in the __init__.py file like making the module _math and then changing the name in __init__.py somehow, or some special way to import the system module instead of myself.

My ugly solution so far:

ldb/
    algebra/
        extra_package/
            __init__.py - empty
            sys_math.py

Contents of sys_math.py:

import math

sin = math.sin

1 Answer 1

2
from __future__ import absolute_import

Put that at the top of your module to disable implicit relative imports. Then import math will import the built-in math module, and if you want to use relative imports, you have to do them explicitly with syntax like from . import math.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes much better idea; disable relative importing.
After fixing some unrelated issues that worked like a charm. Thanks. Also, thanks for the ref to pep-0328, I was wondering where all that stuff I remembered reading before was.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.