python3: conditional import from one of two packages - python

I have two packages fast and slow which are "api compatible" with each other.
If fast is available I want to import from it, else from slow.
My current working solution is
import imp
try:
imp.find_module('fast')
from fast.UtilityFunctions import UtilityFunctions
from fast.Utilities.Log import Log
from fast.model.device_driver import DriverModel
...
except ImportError:
from slow.UtilityFuntions import UtilityFunctions
...
# normal code
It there a better way to write this? Can I eliminate the copy paste job above?
i.e. what would be the pythonic equivalent of this pseudo-code?
import imp
try:
imp.find_module('fast')
alias found=fast
except ImportError
alias found=slow
from found.UtilityFuntions import UtilityFunctions
...

Why don't you just import the modules directly?
try:
import fast as found
except ImportError:
import slow as found
from found.UtilityFuntions import UtilityFunctions

try:
import some_specific_module as module
except ImportError:
import other_module
Try this piece of code!

Related

Python Error : Cannot import name 'Mapping' from 'collections'

When I try to run my project I get this error. I've seen alot of people having this issue on here and I've tried their codes but It didn't work. I'm using Python 3.10.6. Where should I fix to solve it?
Error
ImportError: cannot import name 'Mapping' from 'collections' (/Users/User/.pyenv/versions/3.10.6/lib/python3.10/collections/__init__.py)
init.py
import _collections_abc
import sys as _sys
from itertools import chain as _chain
from itertools import repeat as _repeat
from itertools import starmap as _starmap
from keyword import iskeyword as _iskeyword
from operator import eq as _eq
from operator import itemgetter as _itemgetter
from reprlib import recursive_repr as _recursive_repr
from _weakref import proxy as _proxy
try:
from _collections import deque
except ImportError:
pass
else:
_collections_abc.MutableSequence.register(deque)
try:
from _collections import defaultdict
except ImportError:
pass
Mapping class was introduced in Python 3.3
Try upgrading to a newer version of Python.

Automate import modules

I have this to import all modules if they dont exist, the thing is that even if i have them it also behaves has if i dont, what am i doing wrong?
listimport=["request","shutil","shutil","styless","time","tkinter","openpyxl","html","datetime","importlib","string",
"easygui","bs4","webbrowser","glob","tarfile","webbrowser","pathlib","platform","subprocess","tkinterweb",
"jira","numpy","matplotlib","calendar","sys","math","math","parser","pyautogui","dateutil","xlwt"]
for x_imp in listimport:
try:
import x_imp
except ImportError as e:
os.system('pip install ' + x_imp)
this always tries to install all modules even if they already exist, any ideas?
When you import a module you do it like this:
import request
Using your program you will try to import every string like this:
import "request"
Because listimport contains strings! so you will get an error every time!
You can fix it using __import__ that do the same thing, but on a string:
import os
listimport = ["request","shutil","shutil","styless","time","tkinter","openpyxl","html","datetime","importlib","string",
"easygui","bs4","webbrowser","glob","tarfile","webbrowser","pathlib","platform","subprocess","tkinterweb",
"jira","numpy","matplotlib","calendar","sys","math","math","parser","pyautogui","dateutil","xlwt"]
for x_imp in listimport:
try:
__import__(x_imp)
except ImportError as e:
os.system('pip install ' + x_imp)
You are now trying to import a string, for example import "numpy". A simple solution can be to use exec()
listimport=["request","shutil","shutil","styless","time","tkinter","openpyxl","html","datetime","importlib","string",
"easygui","bs4","webbrowser","glob","tarfile","webbrowser","pathlib","platform","subprocess","tkinterweb",
"jira","numpy","matplotlib","calendar","sys","math","math","parser","pyautogui","dateutil","xlwt"]
for x_imp in listimport:
try:
exec('import {}'.format(x_imp))
except ImportError:
os.system('pip install ' + x_imp)

ModuleNotFoundError: No module named 'SessionState

I am trying to make use of the streamlit SessionState, when I import SessionState. I get the following error: ModuleNotFoundError: No module named 'SessionState'
when using he SessionState
Here is a snipnet of my code:
from multiprocessing import Process
import streamlit as st
import SessionState
import time
import os
import signal
st.sidebar.title("Controls")
start = st.sidebar.button("Start")
stop = st.sidebar.button("Stop")
state = SessionState.get(pid=None)
Has anyone encountered this and how did you fix it? There are no resources online
https://docs.streamlit.io/en/stable/changelog.html?highlight=SessionState#version-0-54-0
Seems like you have to download this gist and put it into your project in order to use SessionState

Python cannot import from another file name not defined

I am trying to import a custom function from another python file but keep getting an error NameError: name 'testme' is not defined. I confirmed that I am importing the file correctly according to this SO post and that the function is top level. What else can I try to fix this?
My main python file is:
import sys
import dbconn
#from dbconn import testme #<----did not work
dev=True
if(dev):
categId='528'
pollIds=[529,530,531]
else:
categId=str(sys.argv[1])
pollIds=[529,530,531]
df=testme(categIds)#callServer(categId,pollIds)
df
if(not categId.isdigit):
print('categ id fail. expected digit got: '+categId)
.....
and dbconn.py:
import pymysql #pip3 install PyMySQL
import pandas as pd
from scipy.stats.stats import pearsonr
from scipy import stats
def testme(categIds):
try:
df=categIds
except Exception as e:
print("broke")
return categIds
Not sure if it makes a difference but I am running the main python file from within a Jupyter notebook, and have a compiled version of dbconn.py in the same directory
In response to the suggestions I tried:
df=dbconn.testme(categIds)
got the error:
module 'dbconn' has no attribute 'testme'
You Have to follow these fox exact import
1)import <package>
2)import <module>
3)from <package> import <module or subpackage or object>
4)from <module> import <object>
in your case, you have tried
from dbconn import testme
you have to use only packages in from section and module in import section
like >>
from testme import dbconn

Dynamic import of several names from a module

I am trying to import some symbols from one package into another. I have tried the following, with no luck as both are syntax errors.
from signal import SIG*
or
import _signal
import _re
from signal import [i for i in dir(_signal) if _re.search("^SIG",i)!=None ]
Is there a way to do this.
Use importlib:
import importlib
mod = importlib.import_module('signal')
loc = locals()
for name in dir(mod):
if name.startswith('SIG'):
loc[name] = getattr(mod, name)
del mod, loc, importlib

Categories