Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import a module in Python only if it doesn't already exist

Tags:

python

module

I want to use a module, e.g. BeautifulSoup, in my Python code, so I usually add this to the top of the file:

from BeautifulSoup import BeautifulSoup

However, when I distribute the module I'm writing, others may not have BeautifulSoup, so I'll just include it in my directory structure like so:

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----         9/19/2011   5:45 PM            BeautifulSoup
-a---         9/17/2011   8:06 PM       4212 myscript.py

Now, my modified myscript.py file will look like this at the top to reference the local copy of BeautifulSoup:

from BeautifulSoup.BeautifulSoup import BeautifulSoup, CData

But what if the developer who uses my library already has BeautifulSoup installed on their machine? I want to modify myscript.py so that it checks to see if BeautifulSoup is already installed, and if so, use the standard module. Otherwise, use the included one.

Using Pseudo-python:

if fBeautifulSoupIsInstalled:
    from BeautifulSoup import BeautifulSoup, CData
else:
    from BeautifulSoup.BeautifulSoup import BeautifulSoup, CData

Is this possible? If so, how?

like image 449
Ben McCormack Avatar asked Sep 19 '11 22:09

Ben McCormack


People also ask

How do you check if a module is already imported in Python?

Use: if "sys" not in dir(): print("sys not imported!")

How do I import a specific module in Python?

You need to use the import keyword along with the desired module name. When interpreter comes across an import statement, it imports the module to your current program. You can use the functions inside a module by using a dot(.) operator along with the module name.

Does Python import module multiple times?

So each module is imported only one time. To better understand import mechanics I would suggest to create toy example. So import really happens only once. You can adjust this toy example to check cases that are interesting to you.


1 Answers

Usually the following pattern is used to handle this situation in Python.

First rename your BeautifulSoup module something else, e.g. MyBeautifulSoup

Then:

try:
    import BeautifulSoup # Standard
except ImportError:
    import MyBeautifulSoup as BeautifulSoup # internal distribution
like image 166
Mikko Ohtamaa Avatar answered Nov 05 '22 11:11

Mikko Ohtamaa