cloud pickle current class with all its variable values - python-3.x

I am having sample program with file name myAutocomplete.py and want to return instance of class
import cloudpickle
class Autocomplete(object):
def __init__(self):
self.test = " Test String "
def assign_value(self):
self.test = "Hello"
return self.test
def get_value(self):
return self.test
#staticmethod
def save(path):
with open(path, "wb") as f:
cloudpickle.dump(Autocomplete, f)
#staticmethod
def load(path):
with open(path, "rb") as f:
test = cloudpickle.load(f)
return test
and another file with name main.py
from myAutocomplete import Autocomplete
if __name__ == '__main__':
testobj = Autocomplete()
testobj.assign_value()
testobj.save("test.pkl")
test = testobj.load("test.pkl")
print(test().get_value())
i expecting output as
"Hello"
but i am getting output as
"Test String"
plz help

Related

Duplicate a string in Tkinter when redirecting output to a text field

I redirect all my output to the program text field in Tkinter and I wanted to add a date and time to the message:
class StdRedirector(object):
def __init__(self, text_field):
self.text_field = text_field
def write(self, string):
msg_time = datetime.now().strftime('%m-%d %H:%M:%S')
self.text_field.configure(state='normal')
self.text_field.insert('end', f'{msg_time} >> {string}')
self.text_field.see('end')
self.text_field.configure(state='disabled')
class App:
def __init__(self):
self.builder = pygubu.Builder()
self.__init_ui()
self.__init_callbacks()
self.mainwindow.mainloop()
def __init_ui(self):
self.builder.add_from_file(path.join(base_dir, 'assets', 'app.ui'))
self.mainwindow = self.builder.get_object('mainwindow')
self.output_text_field = self.builder.get_object('output_text_field')
sys.stdout = StdRedirector(self.output_text_field)
sys.stderr = StdRedirector(self.output_text_field)
def __init_callbacks(self):
callbacks = {
'update_balance_function': self.__update_balance
}
self.builder.connect_callbacks(callbacks)
def __update_balance(self):
print(True)
But the date line I added is duplicated:
As I understand it, the line is separated by the line separator \n and each substring is sent separately, including line break. Can I fix it somehow?
You can simply check whether the string argument in write() contains any meaningful content, e.g. using ìf string.strip():
class StdRedirector(object):
def __init__(self, text_field):
self.text_field = text_field
def write(self, string):
self.text_field.configure(state='normal')
if string.strip(): # add date before message
msg_time = datetime.now().strftime('%m-%d %H:%M:%S')
self.text_field.insert('end', f'{msg_time} >> {string}')
else: # simply insert string
self.text_field.insert('end', string)
self.text_field.see('end')
self.text_field.configure(state='disabled')

compile error in vs code when using python decorator

import yaml, os
import logging.config
def setup_logging(default_path='logging.yaml', default_level=logging.INFO, env_key='LOG_CFG'):
"""load logging.yaml file or use system environment variable 'LOG_CFG' to setup logging configuration"""
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path, 'rt') as f:
config = yaml.safe_load(f.read())
logging.config.dictConfig(config)
else:
logging.basicConfig(level=default_level)
def logger_decorate(cls: type):
"""logger decorator for each class"""
# setup logging
setup_logging()
aname = '_{}__log'.format(cls.__name__)
setattr(cls, aname, logging.getLogger(cls.__module__ + '.' + cls.__name__))
return cls
#logger_decorate
class Test(object):
def __init__(self, name):
self.name = name
def sayHello(self):
self.__log.info('sayHello called')
print("hello", self.name)
def test(self):
self.__log.info('test called')
getattr(self, 'sayHello')()
test = Test("john")
test.test()
will print
2018-09-28 00:30:51,881 - main.Test - INFO - test called
2018-09-28 00:30:51,882 - main.Test - INFO - sayHello called
hello john
but there will be compile error in the vscode, anyone knows how to fix this?
In the meanwhile, I could figure out a workaround to solve the compile error in the VSCode Editor with adding an attribute with name __log in the class
#logger_decorate
class Test(object):
__log = None # workaround
def __init__(self, name):
self.name = name
def sayHello(self):
self.__log.info('sayHello called')
print("hello", self.name)
def test(self):
self.__log.info('test called')
getattr(self, 'sayHello')()
test = Test("john")
test.test()

with self.driver.session as session: AttributeError: __enter__ when link to neo4j

I want to link to neo4j database and write in some data,but when i run the scripts, here comes the error:
and the source code is:
from neo4j.v1 import GraphDatabase
import pandas as pd
class LeaderNeo4j(object):
def __init__(self, driver):
self.driver = driver
def close(self):
self.driver.close()
def add_relation(self, name, friend_name):
with self.driver.session as session:
session.write_transaction(self.create_relation, name, friend_name)
#staticmethod
def create_relation(tx, name, friend_name):
tx.run("MATCH (d1:Department {department_name: $name}),(d2:Department {department_name: $friend_name})"
"MERGE (d1)-[:下级]->(d2)",
name=name, friend_name=friend_name)
if __name__ == '__main__':
uri = "bolt://localhost:7687"
driver = GraphDatabase.driver(uri, auth=("neo4j", "HBUE112"))
MyNH = LeaderNeo4j(driver)
print(MyNH)
directory = r"D:\Program Files\neo4j-community-3.3.1\import"
f_name = r"bumen.csv"
file_data = pd.read_csv(directory + '\\' + f_name, encoding='utf-8')
for i in range(file_data.shape[0]):
line = file_data.irow(i)
print(line[0], line[1])
MyNH.add_relation(line[0], line[1])
You need to call self.driver.session as a function. Try replacing this line:
with self.driver.session as session:
with this line:
with self.driver.session() as session:

self.assertTrue throwing traceback error in Python 3.x unittesting

I am running a small unittest to check the roman number converter. Here is my code :-
class RomConverter(object):
def __init__(self):
self.digital_mapping = {"M":1000, "D":500, "C":100, "L":50, "X":10, "V":5, "I":1}
def convert(self, rom_num):
value = 0
for char in rom_num:
val += self.digital_mapping[char]
return value
import unittest
class RomConverterTest(unittest.TestCase):
def settingUp(self):
print ("Creating a new RomConverter...")
self.cvt = RomConverter()
def tearDown(self):
print ("Destroying the RomConverter...")
self.cvt = None
def test_empty_num(self):
self.assertTrue(self.cvt.convert("") == 0)
self.assertFalse(self.cvt.convert("") > 0)
def test_no_rom_num(self):
self.assertRaises(TypeError,self.cvt.convert, None)
if __name__ == "__main__":
unittest.main()
But I am getting this message when I run the code :-
Traceback (most recent call last):
File "receipe2 - Copy.py", line 31, in test_empty_roman_numeral
self.assertTrue(self.cvt.convert_to_decimal("") == 0)
AssertionError: False is not true
I see two problems in your code.
First def settingUp(self): should be def setUp(self):
And the return of def convert(self, rom_num): is indented to much. In result the method does not return 0 incase of an empty string.
Here is a working version:
class RomConverter(object):
def __init__(self):
self.digital_mapping = {"M":1000, "D":500, "C":100, "L":50, "X":10, "V":5, "I":1}
def convert(self, rom_num):
value = 0
for char in rom_num:
value += self.digital_mapping[char]
return value
import unittest
class RomConverterTest(unittest.TestCase):
def setUp(self):
print ("Creating a new RomConverter...")
self.cvt = RomConverter()
def tearDown(self):
print ("Destroying the RomConverter...")
self.cvt = None
def test_empty_num(self):
self.assertTrue(self.cvt.convert("") == 0)
self.assertFalse(self.cvt.convert("") > 0)
def test_no_rom_num(self):
self.assertRaises(TypeError,self.cvt.convert, None)
if __name__ == "__main__":
unittest.main()

can't set attribute in class instance in Python

I'm trying to create a instance of a class to test that the module I created is working properly.
Here is the module (fileWriter.py), the error appears to be in the init method:
class File(object):
'''process the data from a file'''
#fields
#fileName = name of file
#textData = data read from/written to file
#Constructor
def __init__(self, fileName = 'saved_data.txt', textData = ''):
#Attributes
self.fileName = fileName
self.textData = textData
#Properties
#property #getter
def fileName(self):
return self.__fileName
#fileName.setter #setter
def fileName(self, value):
self.__fileName = value
#property #getter
def textData(self, value):
self.__textData = value
#Methods
def saveData(self):
'''appends data to file'''
try:
fileObj = open(self.fileName, 'a')
fileObj.write(self.textData)
fileObj.close()
except Exception as e:
print('You have the following error: ' + str(e))
return('Data successfully saved to file.')
def toString(self):
'''returns text data explicitly'''
return self.fileName + ':' + self.textData
def __str__(self):
'''returns text data implicitly'''
return self.toString()
To test the class, I wrote the following test harness:
import fileWriter
import fileWriter
#test harness
processorObj = fileWriter.File()
processorObj.fileName = 'test.txt'
processorObj.textData = 'testing, 1, 2, 3...'
strMessage = processorObj.saveData()
print(strMessage)
if __name__ == '__main__':
raise Exception('Don\'t run a module by itself!')
When I run the test file, I get the error:
File "testFileWriter.py", line 4, in
processorObj = fileWriter.File()
File "/Users/Haruka/Documents/python_class/Employees/fileWriter.py", line 19, in init
self.textData = textData
AttributeError: can't set attribute
I can't figure out what's wrong with self.textData = textData. Can anybody help?
I'm not sure if you formatted your code after pasting, but there are a few typos:
def __init__(self, file_name = 'saved_data.txt', text_data = ''):
#Attributes
self.__file_name = file_name
self.__text_data = text_data
and
#property #getter
def text_data(self):
return self.__text_data
Later in test, you're also trying to set the text_data property without a setter in your example. You can add to your class:
#textData.setter
def text_data(self, value):
self.__text_data = value
The more pythonic way to do some of the file io stuff is with a context.
def save_data(self):
'''appends data to file'''
with open(self.file_name, 'a') as f:
f.write(self.text_data)
return('Data successfully saved to file.')

Resources