1 year ago

#386823

test-img

sdbbs

Import specific items from module file in Python, while ignoring other imports in same module file?

Let's say I have this file as lib_my.py:

import smbus

main_array = [1, 10, 20, 100]

Now, I run this usually on Raspberry Pi Raspbian, where I have the smbus package.

However, now for a test, I'd like to import main_array on Windows, where I do not have smbus (and I'm not sure it can be installed either) - and this is the result:

$ python3
Python 3.9.11 (main, Mar 18 2022, 16:54:01)  [GCC 11.2.0 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> from lib_my import main_array

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:/msys64/tmp/lib_my.py", line 1, in <module>
    import smbus
ModuleNotFoundError: No module named 'smbus'
>>>

So, even if main_array is just a primitive (list of integers), Python still tries to import the whole library first, and as expected, chokes on import smbus.

Is there a way to instruct Python, to import only the requested item (primitive object, class, function), ignoring other imports in the same file (that are otherwise unrelated to the imported item)?

python

python-import

0 Answers

Your Answer

Accepted video resources