2

In my python script, I'm trying to import module in class and use the imported module in the class method.

class test:
    import urllib.parse

    def __init__(self, url):
        urlComponents = urllib.parse.urlsplit(url)

Howerver, when I try to use the test class, such as

test("http://test.com")

I get the error:

NameError: name 'urllib' is not defined

Why import statement in class body do not take effect?

I use python 3.8.1 in windows 10.

2 Answers 2

1

The import statement performs a name binding, but names inside the class scope are not directly visible inside methods. This is the same as for any other class name.

>>> class Test:
...     a = 2   # bind name on class
...     def get_a(self):
...         return a  # unqualified reference to class attribute
...
>>> Test().get_a()
NameError: name 'a' is not defined

You can refer to any class attribute either through the class or the instance instead. This works for imported names as well.

class test:
    import urllib.parse

    def __init__(self, url):
        #               V refer to attribute in class
        urlComponents = self.urllib.parse.urlsplit(url)

Note that there isn't any advantage to binding a module inside a class, with the exception of hiding the name from the global scope. Usually, you should import at the global scope.

import urllib.parse

class test:

    def __init__(self, url):
        #               V refer to global module
        urlComponents = urllib.parse.urlsplit(url)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help. This explaination is very clear and helpful to me.
1

It was self.urllib.parse that you were missing.

If you really want to import a module inside a class you must access it from that class:

class Test:
    import urllib.parse as ul


    def __init__(self, url):
        urlComponents = self.ul.urlsplit(url)

t1 = Test("www.test.com")  
print(t1)

Result : <main.Test at 0x5029>

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.