Python Library Reference/Usage - python

I'm trying to use a method from the BioPython package to calculate an isoelectric point for a list of given peptides. The class breakdown can be seen here:
http://biopython.org/DIST/docs/api/Bio.SeqUtils.ProtParam.ProteinAnalysis-class.html#isoelectric_point
In order to import this class to my environment, I'm using the following code (did I do this right?):
from Bio.SeqUtils.ProtParam import ProteinAnalysis
Then, to call the method, I do the following:
window_aas = "ditkdteneveadveveadveveadvseql";
ProteinAnalysis.isoelectric_point(window_aas);
However I'm getting the following error, and I'm not sure how to interpret it, despite several searches for similar errors:
File
"C:\Users\----\AppData\Local\Programs\Python\Python36-32\lib\site-packages\Bio\SeqUtils\ProtParam.py",
line 68, in count_amino_acids
if self.amino_acids_content is None: AttributeError: 'str' object has no attribute 'amino_acids_content'
Is anyone able to guide me in the right direction here? This other class is also called IsoElectricpoint but I don't see a method in it to use:
http://biopython.org/DIST/docs/api/Bio.SeqUtils.IsoelectricPoint-module.html

ProteinAnalysis is a class. What you're doing in your code is trying to call a method in that class directly. In Python, the first argument to such a function is the class object, but you're passing in a string (window_aas). The correct way to use this api is first create a class object:
protein_analysis = ProteinAnalysis(window_aas)
and then you can call
protein_analysis.isoelectric_point()
You can read up more on how this all works in the online docs.

It looks like isoelectric_point is an instance method, so you need to create an instance first:
analysis = ProteinAnalysis(window_aas)
analysis.isoelectric_point()

Related

How to dynamically return Object attributes in python, including attributes of objects that are attributes

I am trying to write a testing program for a python program that takes data, does calculations on it, then puts the output in a class instance object. This object contains several other objects, each with their own attributes. I'm trying to access all the attributes and sub-attributes dynamically with a one size fits all solution, corresponding to elements in a dictionary I wrote to cycle through and get all those attributes for printing onto a test output file.
Edit: this may not be clear from the above but I have a list of the attributes I want, so using something to actually get those attributes is not a problem, although I'm aware python has methods that accomplish this. What I need to do is to be able to get all of those attributes with the same function call, regardless of whether they are top level object attributes or attributes of object attributes.
Python is having some trouble with this - first I tried doing something like this:
for string in attr_dictionary:
...
outputFile.print(outputclass.string)
...
But Python did not like this, and returned an AttributeError
After checking SE, I learned that this is a supposed solution:
for string in attr_dictionary:
...
outputFile.print(getattr(outputclass, string))
...
The only problem is - I want to dynamically access the attributes of objects that are attributes of outputclass. So ideally it would be something like outputclass.objectAttribute.attribute, but this does not work in python. When I use getattr(outputclass, objectAttribute.string), python returns an AttributeError
Any good solution here?
One thing I have thought of trying is creating methods to return those sub-attributes, something like:
class outputObject:
...
def attributeIWant(self,...):
return self.subObject.attributeIWant
...
Even then, it seems like getattr() will return an error because attributeIWant() is supposed to be a function call, it's not actually an attribute. I'm not certain that this is even within the capabilities of Python to make this happen.
Thank you in advance for reading and/or responding, if anyone is familiar with a way to do this it would save me a bunch of refactoring or additional code.
edit: Additional Clarification
The class for example is outputData, and inside that class you could have and instance of the class furtherData, which has the attribute dataIWant:
class outputData:
example: furtherData
example = furtherData()
example.dataIWant = someData
...
with the python getattr I can't access both attributes directly in outputData and attributes of example unless I use separate calls, the attribute of example needs two calls to getattr.
Edit2: I have found a solution I think works for this, see below
I was able to figure this out - I just wrote a quick function that splits the attribute string (for example outputObj.subObj.propertyIWant) then proceeds down the resultant array, calling getattr on each subobject until it reaches the end of the array and returns the actual attribute.
Code:
def obtainAttribute(sample, attributeString: str):
baseObj = sample
attrArray = attributeString.split(".")
for string in attrArray:
if(attrArray.index(string) == (len(attrArray) - 1)):
return getattr(baseObj,string)
else:
baseObj = getattr(baseObj,string)
return "failed"
sample is the object and attributeString is, for example object.subObject.attributeYouWant

convert python2.6 cantera1.8 to python2.7 cantera2.2

I am new on chemical network model. Currently I am converting a previous student python code to adapt the new version in the lab as titled.
firstly, a gas mixture from mechanism (pre defined) is defined
gas_mix = ct.import_phases(mech,['gas'])
then, I want to get the number of the species and use cantera nSpecies
nsp = gas_mix.nSpecies()
and I got the error message as
AttributeError: 'list' object has no attribute 'nSpecies'
Also I tried:
nsp = gas_mix.n_species
and it also shows
AttributeError: 'list' object has no attribute
Would you please kindly help me on this ?
Thank you and best regards,
YouBe
It looks like import_phases returns a list of objects--either a list of "gas mix" or just "gas" objects. I'm not really sure because this is very specific to the program you're working with.
Anyway, try looping over the values in the gas_mix and see if you can call the nSpecies() method or access the n_species attribute:
gas_mix = ct.import_phases(mech,['gas'])
for gm in gas_mix:
print(gm.nSpecies())
# or you can try this:
print(gm.n_species)
Maybe that will get you closer to what you want.
The function import_phases returns a list, which is useful for the case where you want to import multiple phase definitions from the same file, e.g.
mixtures = ct.import_phases(mech, ['gas1', 'gas2'])
where both mixtures[0] and mixtures[2] will then be a single phase definition. If you only want to define a single phase, it is easier to write:
gas_mix = ct.Solution(mech,'gas')
Or, if the mechanism file only contains one phase definition, just
gas_mix = ct.Solution(mech)
From here, you should be able to access the number of species as
gas_mix.n_species
Many of the details of migrating from the old to new Cantera interfaces are described in the documentation page "Migrating from the Old Python Module".

Python - Mocking an object's attribute with multiple values?

I have an object method which changes an attribute of an object. Another method (the one I'm trying to test) calls the first method multiple times and afterward uses the attribute that was modified. How can I test the second method while explicitly saying how the first method changed that attribute?
For example:
def method_to_test(self):
output = []
for _ in range(5):
self.other_method()
output.append(self.attribute_changed_by_other_method)
return output
I want to specify some specific values that attribute_changed_by_other_method will become due to other_method (and the real other_method uses probabilities in deciding on how to change attribute_changed_by_other_method).
I'm guessing the best way to do this would be to "mock" the attribute attribute_changed_by_other_method so that on each time the value is read it gives back a different value of my specification. I can't seem to find how to do this though. The other option I see would be to make sure other_method is mocked to update the attribute in a defined way each time, but I don't know of a particularly clean way of doing this. Can someone suggest a reasonable way of going about this? Thank you much.
What you can actually do is use flexmock for other_method. What you can do with flexmock is set a mock on an instance of your class. Here is an example of how to use it:
class MyTestClass(unittest.TestCase):
def setUp(self):
self.my_obj = MyClass()
self.my_obj_mock = flexmock(self.my_obj)
def my_test_case(self):
self.my_obj_mock.should_receive('other_method').and_return(1).and_return(2).and_return(3)
self.my_obj.method_to_test()
So, what is happening here is that on your instance of MyClass, you are creating a flexmock object out of self.my_obj. Then in your test case, you are stating that when you make your call to method_to_test, you should receive other_method, and each call to it should return 1, 2, 3 respectively.
Furthermore, if you are still interested in knowing how to mock out attribute_changed_by_other_method, you can use Mock's PropertyMock:
Hope this helps. Let me know how it goes!
For anyone still looking for a straightforward answer, this can be done easily with PropertyMock as the accepted answer suggests. Here is one way to do it.
from unittest.mock import patch, PropertyMock
with patch("method_your_class_or_method_calls", new_callable=PropertyMock) as mock_call:
mock_call.side_effect = [111, 222]
class_or_method()
Each subsequent call of that patched method will return that list in sequence.

Constructor and using methods

I have created the following constructor:
class Analysis:
def __init__(self, file_list, tot_col, tot_rows):
self.file_list = file_list
self.tot_col = tot_col
self.tot_rows = tot_rows
I then have the method full_analysis() call calc_total_rows() from the same file:
def full_analysis(self):
"""Currently runs all the analysis methods"""
print('Analysing file...\n' +
'----------------------------\n')
calc_total_rows()
From another file I am calling the full_analysis() however errors occur saying that calc_total_rows() is not defined, and the method is just below it.
I'm inexperienced with Python however I tried to rearrange the code and add 'self' in various places to no avail.
The other file does meet the requirements of the constructor, and if I remove the calc_total_rows() method, the print line runs. I however do not wish to call each method individually, and would like to call a single method which runs them all.
If calc_total_rows is an instance method as your question implies, then you need to call self.calc_total_rows() from within full_analysis. Unlike some other languages, Python does not have implicit instance references within method scope; you have to explicitly retrieve the member method from self.
I wish I had found this sooner.
In order to solve this, I had to use self in front of the method.
In my example:
def full_analysis(self):
"""Currently runs all the analysis methods"""
print('Analysing file...\n' +
'----------------------------\n')
self.calc_total_rows()
This works.

Python sixohsix twitter wrapper

i was looking at sixohsix Twitter wrapper trying to understand the code and found out that for example:
t = Twitter(...)
t.statuses.home_timeline()
Theres no statuses or home_timeline methods or attributes in the Twitter class or TwitterCall, so clearly im missing some python magic in here. Could anyone explain me whats going on there?
thanks so much in advance!
Basically Twitter is a subclass of TwitterCall and the magic takes place in __getattr__. If you're accessing an attribute that doesn't exist you'll get an AttributeError.
When that happens it runs extend_call with that attribute as argument and that'll call self.callable_cls (which also happens to be TwitterCall). This result in another TwitterCall object. The same trick is then repeated because it'll discover that home_timeline doesn't exist on that object either. It'll then call this object (because you're writing home_timeline()) and that makes a HTTP request to Twitter.
The easiest way is to step through the code to see what's going on. When you're accessing an attribute you need to read __getattr__ and when you're making a method call you need to read __call__.
There is, line 141. You should read about __getattr__.
In your example, all attributes not defined for TwitterCall class (or its descendant Twitter), that is, if AttributeError is raised by object.__getattr__, are recursively translated to a call to Twitter API, with uriparts combining all the attributes in a tuple.
So in your example, a call to statuses.home_timeline uri will be made in the end of recursion.

Categories

Resources