Python Class Initialization Error. Cannot initialize an Imported class - python

I am trying to initialize a class ModuleLMPC from commander.py which is the main class. I get following error.
File "D:\CARLA\PythonAPI\examples\fnc\commander.py", line 89, in __init__
self.LMPC = ModuleLMPC(self.dt, self.LapTime, self.maxLaps, self.Map)
TypeError: 'module' object is not callable
I import ModuleLMPC as:
from ModuleLMPC import ModuleLMPC
I am trying to import ModuleLMPC from ModuleLMPC.py file. They have the same name.
The ModuleLMPC first few lines look like:
from SysModel import Simulator, PID
from Classes import ClosedLoopData, LMPCprediction
from PathFollowingLTVMPC import PathFollowingLTV_MPC
from PathFollowingLTIMPC import PathFollowingLTI_MPC
from LMPC import ControllerLMPC
from Utilities import Regression
import numpy as np
import pdb
import pickle
class ModuleLMPC(object):
def __init(self, dt, Time, maxlaps, map):
# ======================================================================================================================
# ============================ Choose which controller to run ==========================================================
# ======================================================================================================================
self.RunPID = 1
self.RunMPC = 1
And I initialize ModuleLMPC in commander.py as:
self.LMPC = ModuleLMPC(self.dt, self.LapTime, self.maxLaps, self.Map)
I even moved everything in the same folder. Not sure what the error means.

Related

Importing a deck in anki python

I am working on an addon, for anki, which requires me to import a new deck using its python API. I found the function called test_apkg which seems to have parts which do that. I tried implimenting that below, I am getting no errors, however the deck does not get imported. How do I make my testFunction() import a deck for anki?
from aqt import mw
from aqt.utils import showInfo, qconnect
from aqt.qt import *
from anki.importing import *
import os
from anki.collection import Collection as aopen
#from anki.pylib.tests.shared import getEmptyCol
from .shared import getEmptyCol
def testFunction() -> None:
file = "flashcards.apkg"
col = getEmptyCol()
apkg = r"path_to_file/flashcards.apkg"
imp = AnkiPackageImporter(col, apkg)
imp.run()
# create a new menu item, "test"
action = QAction("Import", mw)
# set it to call testFunction when it's clicked
qconnect(action.triggered, testFunction)
# and add it to the tools menu
mw.form.menuTools.addAction(action)

Can't import helper functions from module - "cannot import name ..." error

I have two scripts, a main file and a smaller module storing some helper functions. My main script opens with
from collections import namedtuple
import rospy
import serial
from sensor_msgs.msg import Imu, MagneticField
from quaternions import euler_deg2rad, euler2quat_ZYX
and in quaternions.py, I have
from collections import namedtuple
import numpy as np
def euler_deg2rad(yaw, pitch, roll):
....
Attempting to run the main script throws an ImportError: cannot import name 'euler_deg2rad' from 'quaternions'
What's going on here? Is importing namedtuple twice creating a circular dependency? Replacing the 'from' import in the main file with just import quaternions works fine, but I'd rather not import the whole module.

Python - Import module which need to import other module

I made a module that makes a linear regression model and draws a graph.
So the module needs to import some packages such as sklearn and matplotlib.
And I want to import this module to another python file and use it.
I think either of the two python files needs to import the above packages..
which of them needs to import?
In below case, my_module.py should import LinearRegression? or my_module2.py should?
ex)
my_module.py
---------------------------
**from sklearn.linear_model import LinearRegression**?
class myclass:
def a (self):
lr = LinearRegression()
my_module2.py
------------------------------
**from sklearn.linear_model import LinearRegression**?
from my_module import myclass
i = myclass()
i.a()
First you import it in my_module.py, then import * from my_module.py to my_module2.py.
my_module.py
---------------------------
from sklearn.linear_model import LinearRegression
class myclass:
def a (self):
lr = LinearRegression()
my_module2.py
------------------------------
from my_module import *
i = myclass()
i.a()

How can i re-use an initialized class in Python?

I'm trying to access a initialized class in the main application from other modules but don't know how to do it.
Background: i want to update a dataframe with data during the whole execution in the main application.
I have to following application structure (this is an simplified version of the code in my application):
constraints
- test_function.py (separate module which should be able to update the initialized class in the main app)
functions
- helper.py (the class which contains the dataframe logic)
main.py (my main application code)
main.py:
import functions.helper
gotstats = functions.helper.GotStats()
gotstats.add(solver_stat='This is a test')
gotstats.add(type='This is a test Type!')
print(gotstats.result())
import constraints.test_function
constraints.test_function.test_function()
helper.py:
class GotStats(object):
def __init__(self):
print('init() called')
import pandas as pd
self.df_got_statistieken = pd.DataFrame(columns=['SOLVER_STAT','TYPE','WAARDE','WAARDE_TEKST','LOWER_BOUND','UPPER_BOUND','OPTIMALISATIE_ID','GUROBI_ID'])
def add(self,solver_stat=None,type=None,waarde=None,waarde_tekst=None,lower_bound=None,upper_bound=None,optimalisatie_id=None,gurobi_id=None):
print('add() called')
self.df_got_statistieken = self.df_got_statistieken.append({'SOLVER_STAT': solver_stat,'TYPE': type, 'WAARDE': waarde, 'OPTIMALISATIE_ID': optimalisatie_id, 'GUROBI_ID': gurobi_id}, ignore_index=True)
def result(self):
print('result() called')
df_got_statistieken = self.df_got_statistieken
return df_got_statistieken
test_function.py:
import sys, os
sys.path.append(os.getcwd())
def test_function():
import functions.helper
gotstats = functions.helper.GotStats()
gotstats.add(solver_stat='This is a test from the seperate module')
gotstats.add(type='This is a test type from the seperate module!')
print(gotstats.result())
if __name__ == "__main__":
test_function()
In main i initialize the class with "gotstats = functions.helper.GotStats()". After that i can correctly use its functions and add dataframe rows by using the add function.
I would like that test_function() is able to add dataframe rows to that same object but i don't know how to do this (in current code the test_function.py just creates a new class in it's local namespace which i don't want). Do i need to extend the class object with an function to get the active one (like logging.getLogger(name))?
Any help in the right direction would be appreciated.
Make your test_function accept the instance as a parameter and pass it to the function when you call it:
main.py:
import functions.helper
from constraints.test_function import test_function
gotstats = functions.helper.GotStats()
gotstats.add(solver_stat='This is a test')
gotstats.add(type='This is a test Type!')
print(gotstats.result())
test_function(gotstats)
test_function.py:
import sys, os
import functions.helper
sys.path.append(os.getcwd())
def test_function(gotstats=None):
if gotstats is None:
gotstats = functions.helper.GotStats()
gotstats.add(solver_stat='This is a test from the seperate module')
gotstats.add(type='This is a test type from the seperate module!')
print(gotstats.result())

How to trigger a function without importing everything?

I programmed a gateway to a opcua-server with python-opcua.
The gateway is subscribing some values in the opcua. That is working good and fast.
Now I want to call a script that writes to the opcua.
In principle, it works too. But because I have to import the whole gateway(and all opcua stuff), it is very slow...
My Question: Is is possible to trigger a function in my class-instance without imorting everything?
To start e.g. function setBool(), I have to import Gateway...
#!/usr/bin/env python3.5 -u
# -*- coding: utf-8 -*-
import time
import sys
import logging
from logging.handlers import RotatingFileHandler
from threading import Thread
from opcua import Client
from opcua import ua
from subscribeOpcua import SubscribeOpcua
from cmdHandling import CmdHandling
from keepConnected import KeepConnected
class Gateway(object):
def __init__(self):
OPCUA_IP = '1.25.222.222'
OPCUA_PORT = '4840'
OPCUA_URL = "opc.tcp://{}:{}".format(OPCUA_IP, str(OPCUA_PORT))
addr = "OPCUA-URL:{}.".format(OPCUA_URL)
# Setting up opcua-handler
self.client = Client(OPCUA_URL)
self.opcuaHandlers = [SubscribeOpcua()]
# Connect to opcua
self.connecter = KeepConnected(self.client,self.opcuaHandlers)
self.connecter.start()
def setBool(self, client):
"""Set e boolean variable on opcua-server.
"""
path = ["0:Objects","2:DeviceSet"...]
root = client.get_root_node()
cmd2opcua = root.get_child(path)
cmd2opcua.set_value(True)
if __name__ == "__main__":
"""Open connecter when gateway is opened directly.
"""
connect = Gateway()
The only way to prevent a code from runing when importing a module is to put it inside a method:
def import_first_part():
global re
global defaultdict
print('import this first part')
# import happen locally
# because when you do `import re` actually
# re = __import__('re')
import re
from collections import defaultdict
def import_second_part():
print('import pandas')
# really unnecessary check here because if we import
# pandas for the second time it will just retrieve the object of module
# the code of module is executed only in the first import in life of application.
if 'pandas' in globals():
return
global pandas
import pandas
def use_regex():
import_first_part()
# do something here
if __name__ == '__main__':
use_regex()
re.search('x', 'xb') # works fine
I checked that 'pandas' is in global scope before reimport it again but really this is not necessary, because when you import a module for the second time it's just retrieved no heavy calculation again.

Categories

Resources