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
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.
_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
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
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
If you want to import just some methods from class
from GP.MyClass import MyFunction
Related
Suppose I have a module named 'module1', which has many classes. I want to use all of their classes in my main controller main.py . I can import whole module with import module1, however, I assume that the class names in 'module1' are unique and I do not want to reference module1 every time I call its function such as module1.class1().
How can I import the whole contents of a module without explicitly having to state class/function names and still being able to refer to them without stating the module name.
Such as:
# module1.py.
class Class1():
pass
class Class2():
pass
# __main__.py
import module1
# The following will not work.
object1 = Class1()
object2 = Class2()
You can use the * import pattern
from module1 import *
This lets you use everything inside that module without referencing it.
from module1 import *
instance = Class1()
However, this is generally discouraged. For reasons why, some additional reading:
Why is "import *" bad?
https://www.geeksforgeeks.org/why-import-star-in-python-is-a-bad-idea/
This question already has answers here:
What can I do about "ImportError: Cannot import name X" or "AttributeError: ... (most likely due to a circular import)"?
(17 answers)
Closed 6 months ago.
I know the issue of circular imports in python has come up many times before and I have read these discussions. The comment that is made repeatedly in these discussions is that a circular import is a sign of a bad design and the code should be reorganised to avoid the circular import.
Could someone tell me how to avoid a circular import in this situation?: I have two classes and I want each class to have a constructor (method) which takes an instance of the other class and returns an instance of the class.
More specifically, one class is mutable and one is immutable. The immutable class is needed
for hashing, comparing and so on. The mutable class is needed to do things too. This is similar to sets and frozensets or to lists and tuples.
I could put both class definitions in the same module. Are there any other suggestions?
A toy example would be class A which has an attribute which is a list and class B which has an attribute which is a tuple. Then class A has a method which takes an instance of class B and returns an instance of class A (by converting the tuple to a list) and similarly class B has a method which takes an instance of class A and returns an instance of class B (by converting the list to a tuple).
Consider the following example python package where a.py and b.py depend on each other:
/package
__init__.py
a.py
b.py
Types of circular import problems
Circular import dependencies typically fall into two categories depending
on what you're trying to import and where you're using it inside each
module. (And whether you're using python 2 or 3).
1. Errors importing modules with circular imports
In some cases, just importing a module with a circular import dependency
can result in errors even if you're not referencing anything from the
imported module.
There are several standard ways to import a module in python
import package.a # (1) Absolute import
import package.a as a_mod # (2) Absolute import bound to different name
from package import a # (3) Alternate absolute import
import a # (4) Implicit relative import (deprecated, python 2 only)
from . import a # (5) Explicit relative import
Unfortunately, only the 1st and 4th options actually work when you
have circular dependencies (the rest all raise ImportError
or AttributeError). In general, you shouldn't be using the
4th syntax, since it only works in python2 and runs the risk of
clashing with other 3rd party modules. So really, only the first
syntax is guaranteed to work.
EDIT: The ImportError and AttributeError issues only occur in
python 2. In python 3 the import machinery has been rewritten and all
of these import statements (with the exception of 4) will work, even with
circular dependencies. While the solutions in this section may help refactoring python 3 code, they are mainly intended
for people using python 2.
Absolute Import
Just use the first import syntax above. The downside to this method is
that the import names can get super long for large packages.
In a.py
import package.b
In b.py
import package.a
Defer import until later
I've seen this method used in lots of packages, but it still feels
hacky to me, and I dislike that I can't look at the top of a module
and see all its dependencies, I have to go searching through all the
functions as well.
In a.py
def func():
from package import b
In b.py
def func():
from package import a
Put all imports in a central module
This also works, but has the same problem as the first method, where
all the package and submodule calls get super long. It also has two
major flaws -- it forces all the submodules to be imported, even if
you're only using one or two, and you still can't look at any of the
submodules and quickly see their dependencies at the top, you have to
go sifting through functions.
In __init__.py
from . import a
from . import b
In a.py
import package
def func():
package.b.some_object()
In b.py
import package
def func():
package.a.some_object()
2. Errors using imported objects with circular dependencies
Now, while you may be able to import a module with a circular import
dependency, you won't be able to import any objects defined in the module
or actually be able to reference that imported module anywhere
in the top level of the module where you're importing it. You can,
however, use the imported module inside functions and code blocks that don't
get run on import.
For example, this will work:
package/a.py
import package.b
def func_a():
return "a"
package/b.py
import package.a
def func_b():
# Notice how package.a is only referenced *inside* a function
# and not the top level of the module.
return package.a.func_a() + "b"
But this won't work
package/a.py
import package.b
class A(object):
pass
package/b.py
import package.a
# package.a is referenced at the top level of the module
class B(package.a.A):
pass
You'll get an exception
AttributeError: module 'package' has no attribute 'a'
Generally, in most valid cases of circular dependencies, it's possible
to refactor or reorganize the code to prevent these errors and move
module references inside a code block.
Only import the module, don't import from the module:
Consider a.py:
import b
class A:
def bar(self):
return b.B()
and b.py:
import a
class B:
def bar(self):
return a.A()
This works perfectly fine.
We do a combination of absolute imports and functions for better reading and shorter access strings.
Advantage: Shorter access strings compared to pure absolute imports
Disadvantage: a bit more overhead due to extra function call
main/sub/a.py
import main.sub.b
b_mod = lambda: main.sub.b
class A():
def __init__(self):
print('in class "A":', b_mod().B.__name__)
main/sub/b.py
import main.sub.a
a_mod = lambda: main.sub.a
class B():
def __init__(self):
print('in class "B":', a_mod().A.__name__)
I am having an issue with Python imports. I created a module to conveniently import a few classes inside of the module with a single statement. I put all of my imports inside of the init of that module, but it doesn't seem to work.
maindir\
- driver.py
- Utility\
- __init__.py
- UtilityClasses.py
My folder structure looks like the above.
Inside of UtilityClasses I have one a class that I have created called MyClass.
Inside of the init file in the Utility folder, I have code that says:
import UtilityClasses
from UtilityClasses import MyClass
Inside of driver.py I have code that says:
import Utility
myVar = MyClass(param1)
However, when I run this, I get an error telling me that name MyClass is not defined.
In __init__.py, you can do
from UtilityClasses import *
from SomeOtherFile import *
This will import everything from UtilityClasses.py and SomeOtherFile.py.
But you still have to access it using the module name
Update: You can access everything like this
In driver.py:
from Utility import *
a = MyClass()
b = ClassInSomeOtherFile()
Your code
import Utility
myVar = MyClass(param1)
of course won't work -- MyClass is nowhere mentioned and it won't come magically from nowhere. Explicit is better than implicit:
from Utility import MyClass
myVar = MyClass(param1)
should work like a charm!
Python has complicated namespaces and modules notion, so i unsure about this. Normally python module and something that is imported from it has different names or only module is imported and it's content used by fully qualified name:
import copy # will use copy.copy
from time import localtime # "localtime" has different name from "time".
But what if module has same name as something that i'm importing from it? For example:
from copy import copy
copy( "something" )
Is it safe? Maybe it's some complicated consequences that i can't see?
From PEP8 ( http://www.python.org/dev/peps/pep-0008/#imports):
When importing a class from a class-containing module, it's usually okay to spell this:
from myclass import MyClass
from foo.bar.yourclass import YourClass
If this spelling causes local name clashes, then spell them
import myclass
import foo.bar.yourclass
and use "myclass.MyClass" and "foo.bar.yourclass.YourClass".
I'm trying to import just a variable inside a class from another module:
import module.class.variable
# ImportError: No module named class.variable
from module.class import variable
# ImportError: No module named class
from module import class.variable
# SyntaxError: invalid syntax (the . is highlighted)
I can do the following, but I'd prefer to just import the one variable I need.
from module import class as tmp
new_variable_name = tmp.variable
del tmp
Is this possible?
variable = __import__('module').class.variable
You can't do that -
the import statement can only bring elements from modules or submodules - class attributes, although addressable with the same dot syntax that is used for sub-module access, can't be individually imported.
What you can do is:
from mymodule import myclass
myvar = myclass.myvar
del myclass
Either way, whenever one does use the from module import anything syntax, the whole module is read and processed.The exception is
from module.submodule import submodule
, where, if thesubmodule itself does not require the whole module, only the submodule is processed.
(So, even onmy workaround above , mymodule is read, and executed - it is not made accessible in the global namespace where the import statement is made, but it will be visible, with all its components, in the sys.modules dictionary.
Follow these two steps
Import the class from the module
from Module import Class
Assign new variables to the existing variables from the class
var1=Class.var1
var2=Class.var2