E
E
Evgeny Skuridin2013-12-02 21:21:05
Python
Evgeny Skuridin, 2013-12-02 21:21:05

How to properly import modules in Python so that they can be used inside a class?

Can you please tell me how to import modules correctly so that they can be used inside the class? I'm new to python, and Google offered different options, but I still did not understand which one is more "correct".
Required modules:

from bs4 import BeautifulSoup
from urllib2 import urlopen
import urlparse

Where and how to import them? In the constructor? Right after the class declaration? I don't know how it would be better.
class Olololo:
    from bs4 import BeautifulSoup
    from urllib2 import urlopen
    import urlparse

    def __init__(self):
        from bs4 import BeautifulSoup
        from urllib2 import urlopen
        import urlparse

        self.soup = BeautifulSoup
        self.urlopen = BeautifulSoup
        self.urlparse = BeautifulSoup

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav, 2014-08-26
@Hateman31

It depends on what you need: fewer imports in the main process or in a given place in the code.
If the class will be called frequently, then it is probably better not to place imports in __init__, if 1-2 times for the entire program, why not: the class will be in an external file, say, which means less code in the main file.
Although I would probably take them out of the class, because then the class would most likely be in its own module. Somewhere out there, it was imported, and then you use the class as much as you like.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question