[Python] There is actually a way to import * at the function level [closed]

Discussão em 'Python' iniciado por Stack, Dezembro 18, 2024.

  1. Stack

    Stack Membro Participativo

    This question is more of a way to share something with you readers. Doing import * within a function is not permitted in Python and is generally a bad practice. However, there are times when you actually need to do it to make your life easier and not deal with the following error:

    SyntaxError: import * only allowed at module level


    An example use case (my use case to be precise) is building a generalized MLOps pipeline with a kubeflow component that will ideally only run the .predict function of various ML objects - from scikit learn , to xgboost, to even something that’s cloud native. To add another caveat to this use case, I am loading the pickle file of the ML object. Listing out every package will be tiresome and painful. Hence in this situation, I would really need the import * functionality to work in my function.

    And, probably you might have come across similar situations.

    Well, here is the solution for all of you folks for this problem:

    def foo():
    import <package_name>
    globals.update(vars(<package_name>))



    Once again, I reiterate that this isn’t ideal; however, there are times when you need to do it like - like my use case above.

    Continue reading...

Compartilhe esta Página