1

Here's my defined function which purposely to import my libraries

def all_package():
  import numpy as np
  import pandas as pd
  import matplotlib.pyplot as plt
all_package()

a = pd.Dataframe([1,2,3])
pd is not existed

So, my question is how can I fix my function to make it able to import all libraries

Wallika
  • 49
  • 6
  • 1
    Well… `global`…?! – deceze Mar 22 '21 at 08:49
  • 4
    Why do you want to use a function for this? Why not just do your imports at the top of the file, like how it's normally done? – Karl Knechtel Mar 22 '21 at 08:50
  • It could be possible with `global` as suggested by @deceze, but it would lead to *not pythonic* code. If you really need that, add comments explaining the rationale for future readers/maintainers. – Serge Ballesta Mar 22 '21 at 08:53
  • 1
    Are you really just asking why this happens, or do you want to know how to fix it? – MisterMiyagi Mar 22 '21 at 08:55
  • The discussion in [these comments](https://stackoverflow.com/questions/37067414/python-import-multiple-times#comment61701388_37067414) might interest you as well, @Wallika – lucidbrot Mar 22 '21 at 09:02

1 Answers1

2

The most clean way to standardize imports is to make a new file, maybe standard_imports.py containing the following:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

Then, in your main script, you can easily import everything using:

from standard_imports import *

Some other less neat options:

def all_package():
    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    return np, pd, plt
np, pd, plt = all_package()

This still makes a function without side side effects in the global scope, but assuming the goal is to use this function in many modules, means adding a package would involve changing every module.

The simplest way is to use the global keyword, but it is generally bad practice to change the global scope in a function. The global keyword is considered a code smell usually:

def all_package():
    global np, pd, plt
    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt

all_package()
mousetail
  • 7,009
  • 4
  • 25
  • 45
  • 1
    lol. That still doesn't answer the OP's question. They didn't ask for solution, they asked the reason. – Nouman Mar 22 '21 at 08:56
  • 1
    @BlackThunder I think the reason is implicitly in that answer that the created "variable" for the imported package name is only in scope inside that function – lucidbrot Mar 22 '21 at 09:01
  • 1
    @lucidbrot I know that. I am talking about the answer mousetail has posted. – Nouman Mar 22 '21 at 10:57