8
votes

I have a GP.py file that I am then running a MyBot.py file from.

In the MyBot.py file, I have the line

from GP import *

I have a suspicion it is importing the whole file instead of just the class methods and class descriptions I want. In the GP.py file, There is code in addition to the defintions

5
It is importing the whole file. There is no way to avoid that. - holdenweb

5 Answers

18
votes

You cannot import class methods separately, you have to import the classes. You can do this by enumerating the classes you want to import:

from GP import class1, class2, class3

Note that this will still load the entire module. This always happens if you import anything from the module. If you have code in that module that you do not want to be executed when the module is imported, you can protect it like this:

if __name__ == "__main__":
    # put code here

Code inside the block will only be executed if the module is run directly, not if it is imported.

5
votes

_single_leading_underscore: weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

Use this instead:

from GP import SomeClass

Have a look at PEP-8 (Python Guidelines) if you want to use import *

Modules that are designed for use via from M import * should use the __all__ mechanism to prevent exporting globals

4
votes

It is not recommended to import all from a module. Zen of Python says "Explicit is better than Implicit"

It may have some side effects by overriding an existing name. You should always keep control on the namespace.

You can import your classes and function this way:

from GP import MyClass, my_function

An alternative is to import the module itself

import GP
GP.my_function()
GP.MyClass()

This way, you create a namespace for the GP module and avoid to overwrite something.

I hope it helps

1
votes

import * indeed import all classes, functions,variables and etc..

if you want to import only specific class use

from GP import class_name

and as far as i know you cannot import only class methods

-3
votes

If you want to import just some methods from class

from GP.MyClass import MyFunction