Can you import libraries in if statements in Python?
I’m working on some code that grabs some data from a website and then transforms it into a data object that will work for whatever machine learning library the user is using. I wanted to do some preprocessing on this data as well to make it easier to work with, but a lot of preprocessing tools are sort of library-specific and I don’t want a user to have to download a library that they aren’t going to use, so I don’t want to just try and import all the libraries I’m trying to support at the top. For example, if a user is using scikit-learn, they shouldnt have to have pytorch installed. I was wondering if I could instead put these import statements in an if statement that does the preprocessing with the tools of the specific library. The code would look something like this: