My python program has the following structure
projectfolder
|--classes
|--__init__.py
|--Exampleclass.py
|--singletons
|--__init__.py
|--Examplesingleton.py
__init__.py
Main.py
Basically, in my main class, I want to create several instances of Exampleclass.py (and other classes from the folder classes) and put them inside an instance of Examplesingleton.py (basically the "World" that is populated by the instances of classes).
The problem is, I always have to call Examplesingleton and Exampleclass like this:
Main.py
import singletons.Examplesingleton as Examplesingleton
import classes.Exampleclass as Exampleclass
test = Exampleclass.Exampleclass("test")
Examplesingleton.Examplesingleton.Exampleclasses.append(test)
Is there a way in Python to reference these classes without typing the Class name twice?
Instead of
Exampleclass.Exampleclass()
I want to write just
Exampleclass()
I tried using
from classes.Exampleclass import Exampleclass
seems to enable that but leads to circular import error messages.
Exampleclass.py:
class Exampleclass:
Somevariable = 0
def __init__(self, somevariable):
self.Somevariable = somevariable
Examplesingleton.py:
class Examplesingleton(object):
Exampleclasses = []
#classmethod
def __init__(cls):
pass
Related
I have a factory as shown in the following code:
class ClassFactory:
registry = {}
#classmethod
def register(cls, name):
def inner_wrapper(wrapped_class):
if name in cls.registry:
print(f'Class {name} already exists. Will replace it')
cls.registry[name] = wrapped_class
return wrapped_class
return inner_wrapper
#classmethod
def create_type(cls, name):
exec_class = cls.registry[name]
type = exec_class()
return type
#ClassFactory.register('Class 1')
class M1():
def __init__(self):
print ("Starting Class 1")
#ClassFactory.register('Class 2')
class M2():
def __init__(self):
print("Starting Class 2")
This works fine and when I do
if __name__ == '__main__':
print(ClassFactory.registry.keys())
foo = ClassFactory.create_type("Class 2")
I get the expected result of dict_keys(['Class 1', 'Class 2']) Starting Class 2
Now the problem is that I want to isolate classes M1 and M2 to their own files m1.py and m2.py, and in the future add other classes using their own files in a plugin manner.
However, simply placing it in their own file
m2.py
from test_ import ClassFactory
#MethodFactory.register('Class 2')
class M2():
def __init__(self):
print("Starting Class 2")
gives the result dict_keys(['Class 1']) since it never gets to register the class.
So my question is: How can I ensure that the class is registered when placed in a file different from the factory, without making changes to the factory file whenever I want to add a new class? How to self register in this way? Also, is this decorator way a good way to do this kind of thing, or are there better practices?
Thanks
How can I ensure that the class is registered when placed in a file different from the factory, without making changes to the factory file whenever I want to add a new class?
I'm playing around with a similar problem, and I've found a possible solution. It seems too much of a 'hack' though, so set your critical thinking levels to 'high' when reading my suggestion below :)
As you've mentioned in one of your comments above, the trick is to force the loading of the individual *.py files that contain individual class definitions.
Applying this to your example, this would involve:
Keeping all class implementations in a specific folders, e.g., structuring the files as follows:
.
└- factory.py # file with the ClassFactory class
└─ classes/
└- __init__.py
└- m1.py # file with M1 class
└- m2.py # file with M2 class
Adding the following statement to the end of your factory.py file, which will take care of loading and registering each individual class:
from classes import *
Add a piece of code like the snippet below to your __init__.py within the classes/ foder, so that to dynamically load all classes [1]:
from inspect import isclass
from pkgutil import iter_modules
from pathlib import Path
from importlib import import_module
# iterate through the modules in the current package
package_dir = Path(__file__).resolve().parent
for (_, module_name, _) in iter_modules([package_dir]):
# import the module and iterate through its attributes
module = import_module(f"{__name__}.{module_name}")
for attribute_name in dir(module):
attribute = getattr(module, attribute_name)
if isclass(attribute):
# Add the class to this package's variables
globals()[attribute_name] = attribute
If I then run your test code, I get the desired result:
# test.py
from factory import ClassFactory
if __name__ == "__main__":
print(ClassFactory.registry.keys())
foo = ClassFactory.create_type("Class 2")
$ python test.py
dict_keys(['Class 1', 'Class 2'])
Starting Class 2
Also, is this decorator way a good way to do this kind of thing, or are there better practices?
Unfortunately, I'm not experienced enough to answer this question. However, when searching for answers to this problem, I've came across the following sources that may be helpful to you:
[2] : this presents a method for registering class existence based on Python Metaclasses. As far as I understand, it relies on the registering of subclasses, so I don't know how well it applies to your case. I did not follow this approach, as I've noticed that the new edition of the book suggests the use of another technique (see bullet below).
[3], item 49 : this is the 'current' suggestion for subclass registering, which relies on the definition of the __init_subclass__() function in a base class.
If I had to apply the __init_subclass__() approach to your case, I'd do the following:
Add a Registrable base class to your factory.py (and slightly re-factor ClassFactory), like this:
class Registrable:
def __init_subclass__(cls, name:str):
ClassFactory.register(name, cls)
class ClassFactory:
registry = {}
#classmethod
def register(cls, name:str, sub_class:Registrable):
if name in cls.registry:
print(f'Class {name} already exists. Will replace it')
cls.registry[name] = sub_class
#classmethod
def create_type(cls, name):
exec_class = cls.registry[name]
type = exec_class()
return type
from classes import *
Slightly modify your concrete classes to inherit from the Registrable base class, e.g.:
from factory import Registrable
class M2(Registrable, name='Class 2'):
def __init__(self):
print ("Starting Class 2")
I need to have this import specifically in the class to prevent my tests having to include the imports for each test (they can't be declared outside because of circular dependency issues with the entire codebase).
I am trying to declare my imports in a class, and access what I need with functions but not too sure how to make this work so that any test can call the functions and get what we need.
I have this at the moment:
class KTestHelper:
""" Small helper class for retrieving our hook and constants"""
from fd.fdee import (
IMOLDER,
KDER,
)
p3 = P3Hook()
#staticmethod
def get_imolder(self) -> str:
return self.IMOLDER
#staticmethod
def get_kder(self) -> str:
return self.KDER
#staticmethod
def get_p3_hook(self) -> P3Hook:
return self.p3
self obviously no longer exists as i added #staticmethod but now i'm not sure how to get it to work properly.
I need to be able to do KTestHelper.get_imolder() on every test function / some test functions that need it.
This strategy isn't enough to prevent the module import. The class will be constructed during the module load and the class attributes get evaluated. Example:
test/
__init__.py
a.py
b.py
c.py
a.py
print("loading module a")
class A:
pass
b.py
print("loading module b")
class B:
from .a import A
c.py
from test.b import B
This will output:
loading module b
loading module a
If you want this to work you'll need to put the import line in the class methods themselves.
print("loading module b")
class B:
#classmethod
def a(cls):
from .a import A
return A
I have a script that I am currently working on, named exp1.py and it's located in
/project/exp1.py
In this script, I am trying to call a function named computelikelihood(), which is inside the class Class(), which is in script method.py, in a different directory:
/project/methods/c_CLASS/method.py
So, in my code in exp1.py, I do this:
import sys
sys.path.append('/project/methods/c_CLASS/')
Which gets me to the folder where method.py is located, but when I want to call the Class() from the method.py, so that I get the function computelikelihood(), that I actually want, I get error. I try this:
from method import Class
from Class import computelikelihood
But I get ImportError: No module named Class. Can anyone help?
EDIT
This is how the __init__ of my Class looks like:
class Class:
def __init__(self,e2wl,w2el,label_set):
self.e2wl = e2wl
self.w2el = w2el
self.workers = self.w2el.keys()
self.examples = self.e2wl.keys()
self.label_set = label_set
Since you are trying to use a method from a Class, you should do so via the class. Do not import the function alone as it isn't intended to be used as such:
from method import Class
Class.computelikelihood()
However, this only works if computelikelihood is a static/class method:
class Class:
#classmethod
def computelikelihood(cls):
...
# or
#staticmethod
def computelikelihood():
...
If it's an instance method:
class Class:
def computelikelihood(self):
...
You'll need to first instantiate an object of class Class:
from method import Class
classObject = Class()
classObject.computelikelihood()
Here is is the directory structure:
->src/dir/classes.py
->src/run.py
# classes.py
class A():
def methA():
# class A
class B():
def MethB():
# class B
class C():
def methC():
# class C
then i need to import Class A in run.py file.
from dir.classes import A
A.methA()
i already tried with using from dir.classes import A but it gives me
ModuleNotFoundError: No module named 'dir.classes'; 'classes' is not a package error
So how can i do that?
You need to put__init__.py file on your dir folder.
This way dir will be recognized as python package.
First, you must have __init__.py in each directory for Python to recognize them as packages.
Then, you should use from dir.classes import A. A is the name of the class, you shouldn't use Class A
Trying to write a python package and I cant create an instance of a class in one of my source files.
package layout is:
-packagedir
----README.md
----setup.py
----packagename
--------__init__.py
--------package.py
--------modules
------------file1.py
------------file2.py
in init.py within packagename i have:
from . modules import file1
from . modules import file2
The file file1.py contains a class:
class File1():
def __init__(self):
self.val = 0
# Other methods and such
The file file2.py contains a class:
class File2():
def __init__(self):
self.type = 0
# Other methods and such
and in package.py I have a class as thus:
class Aclass(file1.File1, file2.File2):
def __init__(self):
# nothing important in here yet
I have build and installed my package like this:
python3 setup.py sdist
sudo pip3 install dist/package-0.1.tar.gz
Now I create a file called test.py and put in it the following:
import package
iss = package.Aclass()
when I run the test file i get the following error:
AttributeError: module 'usbiss' has no attribute 'Aclass'
I do not understand why it is that python is not letting me create an instance of class Aclass and thinks I am accessing an attribute. I am sure there is something fundamentally wrong with my import statements or something but i am at a loss as to what it is. How do I correct this so that I can create an instance of Aclass and use its methods?
Thanks.
The problem here was that I was importing the package itself but not a module within that package. I changed my import in test.py to:
from package import package
and this fixed my issue.
Are you sure you are handling your import properly and not introducing any circular dependencies?
Also:
def __init__(file1.File1, file2.File2):
def __init__():
Your init methods are lacking self. They should be:
def __init__(self, file1.File1, file2.File2):
def __init__(self):