-1

I have a class object and some of the methods in the object require python packages (e.g. numpy). If I import the packages in the main script prior to creating the object the methods in the object do not recognize that the packages were imported. To fix this I have to import all necessary packages within the method itself which seems inefficient since the method is called numerous times. Is there any other way to ensure the methods can find previously imported packages?

Here is the class object:

class CCState:
    def __init__(self, stateVector = None):
        self.fill_vol = 0
        self.headspace_vol = 0
        self.temperature = 0
        self.pressure = 0
        self.flowin = 0
        self.flowout = 0
        self.product = 0
        self.viacell_attach = 0
        self.viacell_suspend = 0
        self.deadcell_attach = 0
        self.deadcell_suspend = 0
        self.headspace_temperature = 0
        self.hdgas_o2 = 0
        self.hdgas_n2 = 0
        self.hdgas_co2 = 0
        self.hdgas_ar = 0
        self.dsg_o2 = 0
        self.dsg_n2 = 0
        self.dsg_co2 = 0
        self.dsg_ar = 0
        self.glucose = 0
        self.glutamine = 0
        self.glutamate = 0
        self.lacticacid = 0
        self.lactate = 0
        self.ammonia = 0
        self.ammonium = 0
        self.bicarbonate = 0
        self.carbonate = 0
        self.cation = 0
        self.proton =  0
        self.anion = 0
        self.hepes = 0
        self.hepesion = 0
        self.hydroxyl = 0
        self.microcarrier = 0
        self.antifoam = 0
        self.sulfite = 0
        self.rDTT = 0
        self.oDTT = 0
        self.promoter = 0
        self.sulfiteacid = 0
        self.sulfate = 0
        self.bisulfite = 0
        self.fudgeacid = 0
        self.fudgeanion = 0
        self.fudgebase = 0
        self.fudgecation = 0
        self.viacell_attach2 = 0
        self.serum = 0
        self.tris = 0
        self.triscation = 0
        self.aceticacid =0
        self.acetate = 0
        self.h3po4 = 0
        self.dihydrogenphosphate = 0
        self.hydrogenphosphate = 0
        self.phosphate = 0
        self.names = [i for i in self.__dict__.keys() if i[:1] != '_']

        # If a vector has been passed, assign all parameters to values in the vector
        if stateVector is not None:
            for iName in range(0,len(self.names)):
                setattr(self,self.names[iName],stateVector[iName])
    def pH(self):
        """Return pH"""
        #from math import log
        return -log(max(10E-14, self.proton)*0.001,10);

If I run this code I get the error "NameError: name 'log' is not defined"

from helper_functions import *
from scipy.integrate import ode
from math import exp, log
from scipy import interpolate
import numpy as np
from numpy.linalg import norm
from CCState import *
import chemical_reaction_model
import time

temp = CCState()
print(temp.pH())
Mike49
  • 473
  • 1
  • 5
  • 17
  • 2
    Could you post your code? Importing python packages at the start of a file *should* allow the packages to be used in each method – Brydenr Dec 12 '19 at 15:54
  • Actually you should __not__ do imports in methods or functions. But if your class is not in your main script, you have to import numpy in your class's module, not in the main script (well, if you need it in your main script you have to import numpy there too of course). – bruno desthuilliers Dec 12 '19 at 15:57
  • @brunodesthuilliers I am trying not to import in the method but I'm not sure why it's not finding the packages i have imported. When you say import into the class's module, are you suggesting adding the import in \__init__? – Mike49 Dec 12 '19 at 16:04
  • No, at the top of the module where your class is defined. And I kindly suggest you do the full official Python tutorial (and have a look at pep8 too). – bruno desthuilliers Dec 12 '19 at 16:26

2 Answers2

2

Python's import is nothing like C or PHP style includes. Python has no global namespace, each module (or script) is it's own namespace, so each module must explicitely import the libs it depends on.

In your case, the solution is simple: move (or copy) the needed imports in your CCState.py module.

Also, do NOT use wildcard imports (from xxx import *) - this is a sure recipe for maintenance nightmares. Always use explicit imports, even if the lib's doc tells you it's ok to use wildcards.

And finally, module names should be all_lower, not CamelCase.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
-1

First of all, please show us the contents of your script.

If you import the library in your main script, it should be available throughout the complete file. While importing a second python script called lib.py with import lib is not the same as copying the contents from that file into your main script. The libraries you implement in lib.py can however be used by the methods your main script.

Main script

from lib import *

x = [1, 2, 3]
x = numpy.array(x)

print(x)

lib.py

import numpy
Anteino
  • 1,044
  • 7
  • 28