Let's suppose some code like this:
class X:
def myfunc(self):
print "orig"
def new_myfunc(self):
print "new"
X().myfunc()
X.myfunc = new_myfunc
X().myfunc()
where the new function is injected by a cheater.
Some functions can be altered,others not.
I would like to know how i can detect this code change.
For example i could make an dict that contain original function codes( with "func_code" ) and then check if they are changed
but how i can run the check at every "import"? there is a way to edit the autoloader in python?
edit: this is what i would like to do, but automatically for every import,how?
protection = {'X':'myfunc'}
f = {}
class X:
def myfunc(self):
print "orig"
def new_myfunc(self):
print "new"
#system check
for key,value in protection.iteritems():
protectedFunc = getattr(eval(key), value)
f[key] = { value : protectedFunc.func_code}
#cheater code
X.myfunc = new_myfunc
#system check
for key,value in protection.iteritems():
protectedFunc = getattr(eval(key), value)
if f[key][value] != protectedFunc.func_code:
print 'detected'
#call by my app
X().myfunc()
I know several ways for your task. For example you can check md5 or other. As variant you can use diff. Python has support of it one, two.
Related
How to properly call one method from another in python.
I get some data from the AWS S3 bucket after I want to sort this data and write it into a .txt.
import boto3
import string
import json
import collections
def handler(event, context):
print(f'Event: {event}')
s3 = boto3.resource('s3')
bucket = s3.Bucket(event["bucket"])
for obj in bucket.objects.all():
key = obj.key
body = obj.get()['Body'].read()
b = json.loads(body)
c = WordCorrection.create_duplicated_words_file(b)
# WordCorrection.create_duplicated_words_file(WordCorrection.word_frequency(
# WordCorrection.correct_words(b)))
# WordCorrection.spell_words(WordCorrection.dict_spell_words(WordCorrection.unrecognized_words_from_textrtact(b)))
return c
CONFIDENT_LEVEL = 98
class WordCorrection:
def correct_words(data):
spell = SpellChecker()
correct_words_from_amazon = []
for items in data['Blocks']:
if items['BlockType'] == "WORD" and items['Confidence'] > CONFIDENT_LEVEL and {items["Text"]} != spell.known([items['Text']]):
correct_words_from_amazon.append(items['Text'])
correct_words_from_amazon = [''.join(c for c in s if c not in string.punctuation) for s in
correct_words_from_amazon]
return correct_words_from_amazon
def word_frequency(self, correct_words_from_amazon):
word_counts = collections.Counter(correct_words_from_amazon)
word_frequency = {}
for word, count in sorted(word_counts.items()):
word_frequency.update({word: count})
return dict(sorted(word_frequency.items(), key=lambda item: item[1], reverse=True))
def create_duplicated_words_file(word_frequency):
with open("word_frequency.txt", "w") as filehandle:
filehandle.write(str(' '.join(word_frequency)))
I was trying to use self but I cannot see a good result, and from the reason I use
WordCorrection.create_duplicated_words_file(WordCorrection.word_frequency(WordCorrection.correct_words(b)))
but I'm in 100% sure that it is not correct, there is another way to call one method from another?
I think your trouble is the result of a misunderstanding about keywords/namespaces for modules vs classes.
Modules:
In python, files are modules so when you are inside of a file, all functions defined up to that point in the file are "in scope." So if I have two functions like this:
def func_foo():
return "foo"
def func_bar():
return func_foo() + "bar"
Then func_bar() will return "foobar".
Classes
When you define a class using the class keyword, that defines a new scope/namespace. It is considered proper (although technically not required) to use the word self as the first parameter to an instance method, and this refers to the instance the method is called upon.
For example:
class my_clazz:
def method_foo(self):
return "foo"
def method_bar(self):
return self.method_foo() + "bar"
Then if I have later in the file:
example = my_clazz()
ret_val = example.method_bar()
ret_val will be "foobar"
That said, because I did not really utilize object-oriented programming features in this example, the class definition was largely unnecessary.
Your Issue
So for your issue, it seems like your trouble is caused by what appears to be unnecessarily wrapping your functions inside a class definition. If you got rid of the class definition header and just made all of your functions in the module you would be able to use the calling techniques I used above. For more information on classes in Python I'd recommend reading here.
I'm trying to learn OOP but I'm getting very confused with how I'm supposed to run the methods or return values. In the following code I want to run read_chapters() first, then sendData() with some string content that comes from read_chapters(). Some of the solutions I found did not use __init__ but I want to use it (just to see/learn how i can use them).
How do I run them? Without using __init__, why do you only return 'self'?
import datetime
class PrinceMail:
def __init__(self):
self.date2 = datetime.date(2020, 2, 6)
self.date1 = datetime.date.today()
self.days = (self.date1 - self.date2).days
self.file = 'The_Name.txt'
self.chapter = '' # Not sure if it would be better if i initialize chapter here-
# or if i can just use a normal variable later
def read_chapters(self):
with open(self.file, 'r') as book:
content = book.readlines()
indexes = [x for x in range(len(content)) if 'CHAPTER' in content[x]]
indexes = indexes[self.days:]
heading = content[indexes[0]]
try:
for i in (content[indexes[0]:indexes[1]]):
self.chapter += i # can i use normal var and return that instead?
print(self.chapter)
except IndexError:
for i in (content[indexes[0]:]):
self.chapter += i
print(self.chapter)
return self????? # what am i supposed to return? i want to return chapter
# The print works here but returns nothing.
# sendData has to run after readChapters automatically
def sendData(self):
pass
#i want to get the chapter into this and do something with it
def run(self):
self.read_chapters().sendData()
# I tried this method but it doesn't work for sendData
# Is there anyother way to run the two methods?
obj = PrinceMail()
print(obj.run())
#This is kinda confusing as well
Chaining methods is just a way to shorten this code:
temp = self.read_chapters()
temp.sendData()
So, whatever is returned by read_chapters has to have the method sendData. You should put whatever you want to return in read_chapters in a field of the object itself (aka self) in order to use it after chaining.
First of all, __init__ has nothing to do with what you want to achieve here. You can consider it as a constructor for other languages, this is the first function that is called when you create an object of the class.
Now to answer your question, if I am correct you just want to use the output of read_chapters in sendData. One of the way you can do that is by making the read_chapters a private method (that is if you don't want it to use through the object) using __ in the starting of the name like __read_chapters then make a call to the function inside the sendData function.
Another point to consider here is, when you are using self and don't intend to use the function through the object you don't need to return anything. self assigns the value to the attribute of the current instance. So, you can leave the function read_chapters at self.chapter = i and access the same in sendData.
Ex -
def sendData(self):
print(self.chapter)
I'm not an expert but, the reason to return self is because it is the instance of the class you're working with and that's what allows you to chain methods.
For what you're trying to do, method chaining doesn't seem to be the best approach. You want to sendData() for each iteration of the loop in read_chapters()? (you have self.chapter = i which is always overwritten)
Instead, you can store the chapters in a list and send it after all the processing.
Also, and I don't know if this is a good practice but, you can have a getter to return the data if you want to do something different with (return self.chapter instead of self)
I'd change your code for:
import datetime
class PrinceMail:
def __init__(self):
self.date2 = datetime.date(2020, 2, 6)
self.date1 = datetime.date.today()
self.days = (self.date1 - self.date2).days
self.file = 'The_Name.txt'
self.chapter = []
def read_chapters(self):
with open(self.file, 'r') as book:
content = book.readlines()
indexes = [x for x in range(len(content)) if 'CHAPTER' in content[x]]
indexes = indexes[self.days:]
heading = content[indexes[0]]
try:
for i in (content[indexes[0]:indexes[1]]):
self.chapter.append(i)
except IndexError:
#not shure what you want to do here
for i in (content[indexes[0]:]):
self.chapter.append(i)
return self
# sendData has to run after readChapters automatically
def sendData(self):
pass
#do what ever with self.chapter
def get_raw_chapters(self):
return self.chapter
Also, check PEP 8 Style Guide for naming conventions (https://www.python.org/dev/peps/pep-0008/#function-and-variable-names)
More reading in
Method chaining - why is it a good practice, or not?
What __init__ and self do on Python?
I have developed a Tkinter application which will basically display the test functions inside a test file and the user can select the particular test functions and run pytest on it. It was working well so far as I had only test functions and no classes. Now, there are classes and functions inside it. How do I capture that those functions come inside that particular class? I thought of using regex but there might be functions outside the class too. So, I dont know how to solve this issue.
So far I have something like this:
Test file:
def test_x():
....
def test_y():
....
Source Code:
with open("{}.py".format(testFile), "r") as fp:
line = fp.readline()
while line:
line = fp.readline()
if ("#" not in line) and ("def" and "test_" in line):
x = line.split()[1].split('(')[0]
gFunctionList.append([testName, x])
Based on which all selected:
#var2State is the checkbutton states
for j in range(len(var2State)):
if var2State[j].get() == 1:
runString += "{}.py::{} ".format(gFunctionList[j][0],
gFunctionList[j][1])
else:
continue
if runString != "":
res = os.system("pytest " + runString)
From the above code, it will run: pytest testFile.py::test_x if test_x is selected.
Now if the test file is like this:
Class test_Abc():
def test_x():
....
def test_y():
....
def test_j():
....
Class test_Xyz():
def k():
....
def test_l():
....
Class test_Rst():
def test_k():
....
def ltest_():
....
Now, if test_l is selected, it should run: pytest testFile.py::test_Xyz::test_l.
But how do I get the test_Xyz above?
if test_j is selected, it should run: pytest testFile.py::test_j.
So, how do I capture the class name right outside a particular set of test functions and not capture if it's not inside the class?
I am not really that familiar with Tkinter or how things get selected, but this might point you in the right direction.
As the link I provided in the comments indicates, instances (i.e. classes) do not have names. If you want to give an instance a name, you just need to include it in the def __init__(self):. When any method (i.e. function) from test_ABC (which also inherits self) is called, you will always have access to self.name.
class test_Abc():
def __init__(self):
self.name = 'test_Abc'
def test_x(self):
return self.name
def test_y(self):
return self.name
abc = test_Abc()
a = abc.test_x()
print('pytest testFile.py::' + a + '::test_x')
which returns:
pytest testFile.py::test_Abc::test_x
I want to generate automatically the button-connections... but dont work:
self._ = {}
j = 0
for i in self.btn:
self._[i] = 'self._' + repr(j)
print self._[i]
self.button[i].clicked.connect(self._[i])
j += 1
should bind the button[i] at the function _j ( def _1(self): / def _2(self): / ... but at execute:
connect() slot argument should be a callable or a signal, not 'str'
how to fix it?
The error message says it all, you need to pass a function or signal. Try to use getattrto get the function the string is representing.
Something like this may work
self.button[i].clicked.connect(getattr(self, '_'.format(j)))
Try creating an actual callable method instead of sending the string to connect():
def make_slot(self, i):
print 'clicked %i' % i
self._ = {}
for i in self.btn:
slot = self.make_slot(i)
self._[i] = slot
self.button[i].clicked.connect(slot)
(The make_slot function is to prevent python late-binding quirkiness, see Creating functions in a loop about that)
Also, instead of building a dict, maybe you could add the slots directly to self:
setattr(self, 'on_button_%i_clicked' % i, slot) # perhaps more convenient?
That way, you could refer to them separately as self.on_button_42_clicked if you need too.
I am maintaining a little library of useful functions for interacting with my company's APIs and I have come across (what I think is) a neat question that I can't find the answer to.
I frequently have to request large amounts of data from an API, so I do something like:
class Client(object):
def __init__(self):
self.data = []
def get_data(self, offset = 0):
done = False
while not done:
data = get_more_starting_at(offset)
self.data.extend(data)
offset += 1
if not data:
done = True
This works fine and allows me to restart the retrieval where I left off if something goes horribly wrong. However, since python functions are just regular objects, we can do stuff like:
def yo():
yo.hi = "yo!"
return None
and then we can interrogate yo about its properties later, like:
yo.hi => "yo!"
my question is: Can I rewrite my class-based example to pin the data to the function itself, without referring to the function by name. I know I can do this by:
def get_data(offset=0):
done = False
get_data.data = []
while not done:
data = get_more_starting_from(offset)
get_data.data.extend(data)
offset += 1
if not data:
done = True
return get_data.data
but I would like to do something like:
def get_data(offset=0):
done = False
self.data = [] # <===== this is the bit I can't figure out
while not done:
data = get_more_starting_from(offset)
self.data.extend(data) # <====== also this!
offset += 1
if not data:
done = True
return self.data # <======== want to refer to the "current" object
Is it possible to refer to the "current" object by anything other than its name?
Something like "this", "self", or "memememe!" is what I'm looking for.
I don't understand why you want to do this, but it's what a fixed point combinator allows you to do:
import functools
def Y(f):
#functools.wraps(f)
def Yf(*args):
return inner(*args)
inner = f(Yf)
return Yf
#Y
def get_data(f):
def inner_get_data(*args):
# This is your real get data function
# define it as normal
# but just refer to it as 'f' inside itself
print 'setting get_data.foo to', args
f.foo = args
return inner_get_data
get_data(1, 2, 3)
print get_data.foo
So you call get_data as normal, and it "magically" knows that f means itself.
You could do this, but (a) the data is not per-function-invocation, but per function (b) it's much easier to achieve this sort of thing with a class.
If you had to do it, you might do something like this:
def ybother(a,b,c,yrselflambda = lambda: ybother):
yrself = yrselflambda()
#other stuff
The lambda is necessary, because you need to delay evaluation of the term ybother until something has been bound to it.
Alternatively, and increasingly pointlessly:
from functools import partial
def ybother(a,b,c,yrself=None):
#whatever
yrself.data = [] # this will blow up if the default argument is used
#more stuff
bothered = partial(ybother, yrself=ybother)
Or:
def unbothered(a,b,c):
def inbothered(yrself):
#whatever
yrself.data = []
return inbothered, inbothered(inbothered)
This last version gives you a different function object each time, which you might like.
There are almost certainly introspective tricks to do this, but they are even less worthwhile.
Not sure what doing it like this gains you, but what about using a decorator.
import functools
def add_self(f):
#functools.wraps(f)
def wrapper(*args,**kwargs):
if not getattr(f, 'content', None):
f.content = []
return f(f, *args, **kwargs)
return wrapper
#add_self
def example(self, arg1):
self.content.append(arg1)
print self.content
example(1)
example(2)
example(3)
OUTPUT
[1]
[1, 2]
[1, 2, 3]