8

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?

3
  • 1
    Taken from effbot.org/zone/import-confusion.htm : When Python imports a module, it first checks the module registry (sys.modules) to see if the module is already imported. If that’s the case, Python uses the existing module object as is. Commented Sep 19, 2011 at 22:33
  • Try to import it. If it doesn't work, catch the ImportError and import from your local copy. Name your local copy something else (myBeautifulSoup) so it doesn't hide the user installed module. Commented Sep 19, 2011 at 22:38
  • @mwan: Ben doesn't need to know if it's already imported, he needs to know if it's already on the system. Commented Sep 19, 2011 at 23:27

1 Answer 1

16

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.