1

[Edit]: My problem is unrelated to what I’m asking here. My machine has python 2.7 and 3.6 installed. Requests module was installed for 2.7 site-packages but not 3.6

I’m trying to import requests into a sub directory. I’m not aware of the best way to do this

My folder structure is

Project
  - project1
     - sub1
       - sub1.py <—- trying to use requests here
  - tests

But in the future if I want to use requests across the whole project, what’s the most effective was to import it?

Football52
  • 123
  • 3
  • 14
  • Could you explain a bit more of why you were asking this? I'm really curious because it's not a question I've even considered before, so I'm fascinated to work out how you're thinking about imports differently from me to lead to this. Were you thinking about optimising things, so Python doesn't carry out the import loads of times if it's running code from different places in your project? – Tim Sep 26 '19 at 11:51
  • That’s another question I have. I had a problem importing which was just my complete fault. But yes, optimizing imports is a separate topic that would go off topic from this thread. If you have 10 places where you import the same thing, shouldn’t there be a way for global import so importing happens 1 time? – Football52 Sep 26 '19 at 11:56
  • Okay, so are you saying the real answer to your question was "install requests"? – Tim Sep 26 '19 at 12:12
  • Yes.... stupid mistake – Football52 Sep 26 '19 at 12:12
  • Hehe, a good lesson learned, I'm sure! On your other question about import optimisation, the best thing a quick search turned up was this: https://stackoverflow.com/questions/128478/ Someone mentions in a comment that Python caches module imports, so I think the interpreter is already reasonably well optimised for the situation you're describing. I guess `import x` doesn't really mean "load up the code for `x`", it's more a declaration that you're wanting to use `x` in code that follows. It's then up to the interpreter to decide how to enable that to happen in an optimised way. – Tim Sep 26 '19 at 12:22

1 Answers1

0

If you're importing a third-party module, it's fine to just have e.g. import requests at the top of any .py file where you want to use it. As long as it's installed for your project (e.g. you've done pip install requests) you can use it wherever you want.

If you're importing your own code from one place in your project to use in another place, that can require a bit more thought, but I don't think that's your question here.

Tim
  • 1,839
  • 10
  • 18