Importing an class and its functionalities from one file to another - python-3.x

I am basically working with python(beginner) on jupyter notebook and stuck on importing a python file into another python file.I am working on an assignment it has 2 files a , b while making a class in file 'a' and importing that file into b to test the function that i have implemented in class of file a but didn't get answer
I tried this line for importing file 'a' in 'b' like this but unable to import

To demonstrate you i created a little sample.
Both files are in the same directory.
# file: a.py
class A:
def printing_method(self):
"""this is the method that prints the output"""
print('Class A said: hello world')
# file: b.py
# import class A from module a
from a import A
class B:
def not_printing_method(self):
"""here we create an instance of the imported class A"""
a_instance = A()
# call the method of class B to print
a_instance.printing_method()
# Create an instance of class B
b_instance = B()
# Call the printing method of class A through the not printing method of class B
b_instance.not_printing_method()

Related

Using multiprocessing.Pool in Python with a function returning custom object

I am using multiprocessing.Pool to speed up computation, as I call one function multiple times, and then collate the result. Here is a snippet of my code:
import multiprocessing
from functools import partial
def Foo(id:int,constant_arg1:str, constant_arg2:str):
custom_class_obj = CustomClass(constant_arg1, constant_arg2)
custom_class_obj.run() # this changes some attributes of the custom_class_obj
if(something):
return None
else:
return [custom_class_obj]
def parallel_run(iters:int, a:str, b:str):
pool = multiprocessing.Pool(processes=k)
## create the partial function obj before passing it to pool
partial_func = partial(Foo, constant_arg1=a, constant_arg2=b)
## create the variable id list
iter_list = list(range(iters))
all_runs = pool.map(partial_func, iter_list)
return all_runs
This throws the following error in the multiprocessing module:
multiprocessing.pool.MaybeEncodingError: Error sending result: '[[<CustomClass object at 0x1693c7070>], [<CustomClass object at 0x1693b88e0>], ....]'
Reason: 'TypeError("cannot pickle 'module' object")'
How can I resolve this?
I was able to replicate the error message with a minimal example of an un-picklable class. The error basically states the instance of your class can't be pickled because it contains a reference to a module, and modules are not picklable. You need to comb through CustomClass to make sure instances don't hold things like open file handles, module references, etc.. If you need to have those things, you should use __getstate__ and __setstate__ to customize the pickle and unpickle process.
distilled example of your error:
from multiprocessing import Pool
from functools import partial
class klass:
def __init__(self, a):
self.value = a
import os
self.module = os #this fails: can't pickle a module and send it back to main process
def foo(a, b, c):
return klass(a+b+c)
if __name__ == "__main__":
with Pool() as p:
a = 1
b = 2
bar = partial(foo, a, b)
res = p.map(bar, range(10))
print([r.value for r in res])

How to import one class and method instead of complete package from one file which is in A package to another Package In Python

Hello everyone please help as I am new to python and I want to know that how I can Import one class from one package to another package
eg:-
In Package A file name is func1.py
Now I want to import only one class lets GoodStudent in another package B in file func2
I have used this in the func2.py file from a package.func1 import GoodStudent but it's giving me o/p of both the class and function.
func1.py
def sum(x, y):
print(x + y)`enter code here`
sum(20,40)
class GoodStudent:
def __init__(self, location, name, age,xyz):
self.location = location
self.name = name
self.age = age
def GoodStudentInformation(self):
print("Name:{}".format(self.name))
print("Age:{}".format(self.age))
def GoodEmployeeInformation(self):
print("xyz:{}".format(self.xyz))
gs = GoodStudent('A', 'B', 7, 'QWERY')
gs.GoodStudentInformation()
gs.GoodEmployeeInformation()
class Employee:

Python - Mock class init that instantiates another class inside

I have the following python file board.py:
def __init__(self, language):
self.foo = Foo(language)
self.words = Aux(self.foo)
And I'm creating this test_file:
#classmethod
def setUpClass(cls):
super().setUpClass()
cls.board = Board('pt')
def test_total_time(self):
self.board.total_time(True)
#some assert
But I'm getting a FileNotFoundError because Aux.___init____() calls a self.foo.method() that opens a file and reads from it.
Is there a way to mock self.foo.method(), or the class Aux?
You will want to patch the module. If you give me the name of the test file and the class you are testing. I can finish this answer for you.
In the test file:
import unittest
def BoardTestCase(unittest.TestCase):
#classmethod
def setUpClass(cls):
super().setUpClass()
cls.aux_mock = unittest.mock.patch('file_undertest.Aux')
cls.board = Board('pt')
def test_total_time(self):
self.board.total_time(True)
#some assert
I would suggest using pytest instead of the standard library unittest. Your tests will be written as functions meaning you can reuse the Board class only when needed to. You can set more robust fixtures (Board class test cases) and the mocker extension is more intuitive if you spend the 15 minutes to wrap your head around it.

Define Python class in separate file

# File 1
me = MongoEngine(app) # I want to use my instance of MongoEngine to define new classes like the example in File 2
# File 2
class Book(me.Document):
title = StringField(null=False, unique=True)
year_published = IntField(null=True)
How can i pass the instance me.Document as an Object definition when creating my new classes in a new file. It works if i put them in the same file?
I believe that the answer choosen as answer is not fully correct.
It seems that File1.py is your main script which is executed,
and File2.py is a module which contains a class you wish to use in File1.py
Also based on a previous question of the OP I would like to suggest the following structure:
File1.py and File2.py are located in the same direcory
File1.py
import MongoEngine
from File2 import Book
me = MongoEngine(app)
# according to the documentation
# you do need to pass args/values in the following line
my_book = Book(me.Document(*args, **values))
# then do something with my_book
# which is now an instance of the File2.py class Book
File2.py
import MongoEngine
class Book(MongoEngine.Document):
def __init__(self, *args, **kwargs):
super(Book, self).__init__(*args, **kwargs)
# you can add additional code here if needed
def my_additional_function(self):
#do something
return True
In File 2 perform import of the me object:
from file1 import me
class Book(me.Document):
pass
# ...
Just like any Python object in a file, me can be imported. You can do it like so:
import file1
class Book(file1.me.Document):
#Do what you want here!
Hope I have helped!

save class variable changes with dill

I wrote an application with tkinter that uses classes as structure. Currently I try to implement a "save"-function, so that one can close the application and if it's restarted decide whether to start from scratch or to use already existing aka. pickled data.
I read about the pickle-module and its weakness that it can't save class variables so I decided to use the dill-module instead.
My Problem: dill saves the start values of my class variables, but if I let the user change the class variables (by calling classmethods), the changes are not saved. Is there any way how one can do this with the pickle or dill module?
I created a minimal example that produces the error. You can see that the changes of the instance variables are saved even after calling instance methods that change the variables. Unfortunately it doesn't work with the class variable and it's corresponding class method:
import dill as pickle
from tkinter import *
root = Tk()
# creating class
class Roomie:
# class variable: total number of expenses
num_exp = 0
# init method: every roomie has a name, info for each expense, etc...
def __init__(self,fname,exp=0.00):
self.fname = fname
self.exp = exp
def raiseExp(self):
self.exp += 1
# class method: every time someone spend smth value of class variable num_exp increases by one
#classmethod
def updateExpNum(cls):
cls.num_exp += 1
# saving instance of class in list object
roomie_0 = Roomie("Cthulhu")
roomie_list = [roomie_0]
def pickleRoomies():
file_Name = "debts.pkl"
# open file for writing
fileObject = open(file_Name,'wb')
# write roomie_list to file
pickle.dump(roomie_list,fileObject)
# here we close the fileObject
fileObject.close()
# load all instances and class variables
def loadPickle():
global roomie_list
filepath = "debts.pkl"
file = open(filepath, "rb" )
roomie_list = pickle.load(file)
# create buttons and bind instance and class methods to them
button_0 = Button(root,text="update number of expenses",command=lambda: Roomie.updateExpNum())
button_1 = Button(root,text="raise expense",command=lambda: roomie_list[0].raiseExp())
button_2 = Button(root,text="save changes",command=lambda: pickleRoomies())
button_3 = Button(root,text="load changes",command=lambda: loadPickle())
button_0.pack()
button_1.pack()
button_2.pack()
button_3.pack()
# run GUI
root.mainloop()
# check program
# print instance variable
print("total expenses:",roomie_list[0].exp)
# print class variable
print("number of expenses:", Roomie.num_exp)
# print instance variable
print("name:", roomie_list[0].fname)

Resources