Python import on sub-folders - python

It`s been a while since I create my classes and import them to my script, using
from <folder> import <file>
and my file.py looks like this:
class myClass:
def __init__():
and so on.
However, whenever I want to use this class on my main script, I have to do:
file.myClass()
Is thera a better way so I could use only "myClass()"?

I have recreated the scenario with the following directory structure:
.
├── outer.py
└── some_folder
└── inner.py
You missed the self in __init__ method:
some_folder/inner.py:
class myClass:
def __init__(self):
print("myClass is initiated")
Import the class from the file when you want to directly use the class name.
outer.py:
from some_folder.inner import myClass
some_object = myClass()
Output:
myClass is initiated

Instead of importing the file, you can import the class
from package.module import MyClass

Related

How do I mock a class from a different module in Python?

In Python I have 3 files in the same folder: file1.py, file2.py and test.py
file1.py contains a simple class definition
class MyClass:
def __init__(self, a, b):
self.a = a
self.b = b
print(f"a={a} and b={b}")
file2.py instantiate previous class
from file1 import MyClass
def instantiate_class():
o = MyClass(1,2)
In test.py I'm trying to mock the file1.MyClass from instantiate_class() function
from unittest.mock import patch
from file2 import instantiate_class
with patch("file1.MyClass") as mock_check:
instantiate_class()
print(mock_check.call_args)
Problem is that class MyClass from file2.py is not mocked as the print from the MyClass constructor is called.
Only solution I found to solve this is to change file2.py with:
import file1
def instantiate_class():
o = file1.MyClass(1,2)
Is there a solution to obtain mocking that does not involve changing file1.py and file2.py? I only want to change the test.py file (writing unit tests for existing classes).
I need to mock the file2.mock instead of file1.mock. Like below:
from unittest.mock import patch
from file2 import instantiate_class
with patch("file2.MyClass") as mock_check:
instantiate_class()
print(mock_check.call_args)
reference
where-to-patch

Python - global class that can be reused

I have a config var in the main class that I use a lot and I also pass it to some other instances that pass it to other classes, and so on.
I need a solution that can be used globally, without the need of passing an instance of the config file, and that I can modify as needed (not const).
something that only requires import anywhere and that the data will be the same and up to date.
In Java, I know that I can Autowired and I know that behind the scenes I'll use the exact same instance.
What solution does Python have?
example
util.py
config = None
setConfig(self, config):
self.config = config
getConfig(self):
return self.config
file1.py
....
import util
util.setConfig(4)
file2.py
import util
util.getConfig()
file3.py
import util
util.setConfig(8)
file4.py
import util
util.getConfig()
main.py
file1()
file2() # ==4
file3()
file4() # ==8
file2() # ==8
Thanks

How to get the full path of script where is path getting from method which located in another folder from class?

Let's say so
package1/
main.py == here i'm calling from Utils class that must give me the path of this file where i call it
package2/
utils.py = which must contain method that return path where they call it
from main.py wanna get path of that main.py from packages Utils
Create Utils class like this:
class Utils:
"""docstring for Utils"""
def getRootPath():
pass
def get_current_path(self):
return os.path.realpath(self.filePath)
def __init__(self, filePath):
super(Utils, self).__init__()
self.filePath = filePath
When you initialize your class somewhere just put the name of script where you init you Utils class like this:
utils = Utils(os.path.basename(__file__))
print(utils.get_current_path())
If you wanna get the dirname where you call it so make another method or replace it with
return os.path.dirname(os.path.realpath(self.filePath))
While you wait someone faster you will do it yourself, especially when morons ask so what do you want to do

How to import one class from many classes on one python file

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

'AttributeError: module 'usbiss' has no attribute Aclass' when creating class instance

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):

Categories