Python - importing package classes into console global namespace
You want to use a different form of import.
In projectname/main_stuff/__init__.py
:
from other_stuff import *
__all__ = ["main1", "main2", "main3"]
When you use a statement like this:
import foo
You are defining the name foo in the current module. Then you can use foo.something
to get at the stuff in foo.
When you use this:
from foo import *
You are taking all of the names defined in foo and defining them in this module (like pouring a bucket of names from foo into your module).
Fish
Updated on June 05, 2022Comments
-
Fish almost 2 years
I'm having a spot of trouble getting my python classes to work within the python console. I want to automatically import all of my classes into the global namespace so I can use them without any prefix.module.names.
Here's what I've got so far...
projectname/ |-__init__.py | |-main_stuff/ |-__init__.py |-main1.py |-main2.py | |-other_stuff/ |-__init__.py |-other1.py |-other2.py
Each file defines a class of the same name, e.g. main1.py will define a class called Main1.
My
PYTHONPATH
is the absolute path to projectname/.I've got a python startup file that contains this:
from projectname import *
But this doesn't let me use my classes at all. Upon starting a python console I would like to be able to write:
ob=Main1()
but Main1 isn't within the current namespace, so it doesn't work.
I tried adding things to the
__init__.py
files...In
projectname/__init__.py
:import main_stuff
In
projectname/main_stuff/__init__.py
:import other_stuff __all__ = ["main1", "main2", "main3"]
And so on. And in my startup file I added:
from projectname.main_stuff import * from projectname.main_stuff/other_stuff import *
But to use the classes within the python console I still have to write:
ob=main1.Main1()
I'd prefer not to need the
main1.
part. Does anyone know how I can automatically put my classes in the global namespace when using the python console?Thanks.
==== EDIT ====
What I need is to import a package at the class level, but
from package import *
gives me everything at the module level. I'm after an easy way of doing something like this:for module in package do: from package.module import *
==== ANOTHER EDIT ====
I ended up adding the class imports to my python startup file individually. It's not ideal because of the overhead of maintaining it, but it does what I want.
from class1.py import Class1 from class2.py import Class2 from class3.py import Class3