I need to have an import in __init__() method (because i need to run that import only when i instance the class).
But i cannot see that import outside __init__(), is the scope limited to__init__? how to do?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Imported names are bound to the current scope, so an import inside a function binds to a local name only.
If you absolutely have to import something in
__init__that then needs to be globally avaliable, mark the imported name asglobalfirst:but this usually leads to strange and wonderfully difficult to locate bugs. Don’t do that, just make your imports at module scope instead.
If you need the imported name within other class methods, you could also assign the imported name to a instance variable:
but again, that’s not the best practice to use.