Python class that inherits from itself? How does this work? - python

Relatively new to Python, and I saw the following construct in the PyFacebook library (source here: http://github.com/sciyoshi/pyfacebook/blob/master/facebook/init.py#L660). I'm curious what this does because it appears to be a class that inherits from itself.
class AuthProxy(AuthProxy):
"""Special proxy for facebook.auth."""
def getSession(self):
"""Facebook API call. See http://developers.facebook.com/documentation.php?v=1.0&method=auth.getSession"""
...
return result
def createToken(self):
"""Facebook API call. See http://developers.facebook.com/documentation.php?v=1.0&method=auth.createToken"""
...
return token
what is this doing?
Tangentially related, I'm using PyDev in Eclipse and it's flagging this as an error. I'm guessing that's not the case. Anyway to let Eclipse know this is good?

The class statement there doesn't make the class inherit from itself, it creates a class object with the current value of AuthProxy as a superclass, and then assigns the class object to the variable 'AuthProxy', presumably overwriting the previously assigned AuthProxy that it inherited from.
Essentially, it's about the same as x = f(x): x isn't the value of f on itself, there's no circular dependence-- there's just the old x, and the new x. The old AuthProxy, and the new AuthProxy.

It's using the AuthProxy imported from a different module (check your imports) and deriving from it.

The "former" AuthProxy is created by __generate_proxies (it's not very nice code, there is even an exec and eval in it :)), but the author wanted also define some methods on top of it.

To make Eclipse stop whining about it, do this:
class AuthProxy(AuthProxy): ##UndefinedVariable

Related

How do I take functions that I already made to run a program and put them under a class?

I am making a contact list system for a class project and used tkinter to make my gui and sqlite3 for the database. I made a bunch of methods that have basically solved the problem but I noticed the question paper says that the functions need to be in a class. How do I put these functions under a class without messing everything up. I am using python3.
A function in a module is similar to a static method in a class. Without knowing any of your app's specifics:
If you have a function that does what you want
def f():
return 'g'
and you want to encapsulate it in a class
class Q:
pass
just assign it as a static method to that class
Q.f = staticmethod(f)
Whenever you need to use that function you have to call it via the class
>>> Q.f()
g
This is similar to what happens when you import a module that has functions - you import the module and call the functions using the module name (the functions are module attributes) - modulename.func().
I really have no idea how this fits with your need or what any downsides might be.

Does the existence of a derived class modify a base class, even if the derived class is never used?

I have a base class, Sample and a derived class SignalSample, and the code for both of these classes normally resides within the same file Sample.py.
I import these classes into my main script in the usual way: from Sample import Sample, SignalSample
While chasing down a bug within one of these classes, I noticed some unusual behavior: deleting the code for the SignalSample derived class changed the behavior of the Signal base class.
So my question is, can the existence of a derived class alter a base class, even if the derived class is never instantiated?
To be concrete, I tried the following combinations.
The code for Sample and SignalSample are both in Sample.py. from Sample import Sample, SignalSample is used in my main script to load these classes. Sample objects are instantiated, there are no SignalSample objects instantiated, the code is just there and unused. In this scenario, I get an error which I will call "type 1".
Delete the code for SignalSample inside Sample.py, and remove the ... import SignalSample statement. In this case, I get a different error which I'll call "type 2".
Note that I don't think the errors are coming from the classes themselves (although they may be), it was more that I found it interesting that the behavior of the code seemed to change because there was an inherited class, even though that class was not used.
This is a stripped-down example of my setup, note that this is not an MWE of the source of my bug, as at the moment I don't know where it is coming from, and so I can't even narrow it down. It's not the solution to the bug I'm looking for, just more information on this seemingly strange behavior of class inheritance.
# file Sample.py
class Sample:
def __init__(self):
self._tfile = None
self._filepath = None
def calculate_filepath(self):
return "my/file/path"
__calculate_filepath = calculate_filepath # private copy
def get_histogram(self, histogram_name):
if not self._filepath:
self._filepath = self.calculate_filepath()
if not self._tfile:
from ROOT import TFile # this is a special filetype
self._tfile = TFile.Open(self._filepath, "READ")
histo = self._tfile.Get(histogram_name)
histo.SetDirectory(0)
self._tfile.Close()
return histo
class SignalSample(Sample):
def __init__(self):
# Inherit
Sample.__init__(self)
self._filepath = self.calculate_filepath()
def calculate_filepath(self):
# Overloaded version of the function in Sample
return "my/very/special/filepath"
Note that I chose to call the calculate_filepath method inside get_histogram because I wanted to avoid possible namespace clashes with the derived class. This is also why I try to make the method "private" with the namespace mangling. This is also why I open the special TFile file inside the get_histogram method, although it is nice that I can then also Close this file inside the same function. Perhaps this isn't the correct usage and maybe this related to the source of my problem?
get_histogram looks potentially broken if it is called more than once. You assign the opened file to the instance (on self._tfile), but then close it before returning... that means that next time the method is called not self._tfile will probably (*) evaluate to False, meaning that you then try to call Get on a closed file. If you are using a sane library this would probably throw a nice error telling you this, but I see you're using ROOT so who knows what might happen :)
Probably simplest would be not to store the file on Sample, and just open the file whenever get_histogram is called?
(*) Implicit booliness is sometimes worth avoiding. In particular when what you actually want to check is whether something is None, prefer writing if x is None: ( https://legacy.python.org/dev/peps/pep-0008/#programming-recommendations )
Incidentally, in this example, __calculate_filepath = calculate_filepath # private copy isn't doing anything, since you never actually use it.

python, how to detect attributes or functions that defined in class but never called by the instance of class?

As you know, when the project's code is very large and there are so many attributes and functions defined in a Class, but some of them never be called by the instance of the Class, and maybe some of them has been discarded. Here is a example:
class Foo(object):
""""""
def __init__(self):
self.a = 1
self.b = 2
self.c = 3
...
self.y = 25
self.z = 26
def func1(self):
pass
def func2(self):
pass
def func3(self):
pass
...
...
def func100(self):
pass
if __name__ == '__main__':
f = Foo()
f.func1()
f.func2()
print f.a, f.b, f.z
In the above code, the instance f of class Foo just called func1() and func2(). And how to find all the attributes and functions of class that never called by the instance of class.
I have tried compiler module but that could not solve my question. And dir(my_instance) is just print all the functions and attributes defined the the class.
Thanks in advance.
You can try coverage.py. It's not static analysis, but actually runs your code and records which statements are executed, outputting annotated html or txt as you wish (quite nicely formatted as well). You can then look for functions and methods whose bodies are not executed at all.
This still doesn't take care of unused attributes. And I don't know the answer to that. Maybe comment them out one at a time and see if tests still pass...
It's pretty hard to prove something is or is not used in the general case. Python is a dynamic language; if even one bit of code calls into code the static analyzer doesn't fully analyze, it could be accessing the variables mentioned.
The pylint and flake8 tools will tell you about local and global names that aren't defined prior to use (unless you break them by using from x import * style imports), and about imports that are never used (an import that is never used is usually wrong, but even then, it could be an intentional part of the interface, where linters would have to be silenced), but I don't believe they can tell you that a given attribute is never accessed; after all, someone else could import your module and access said attributes.
Use the profile module in the standard library.
python -m cProfile -o output_file myscript.py
Then load the stats file and use print_callees() to get all the functions that were called--during that run of the program.
I don't know of any easy way to find out which attributes are used.

What is the decorator for turning a function to a field?

At some point I encountered a piece of code like this, written in python:
class Foo(object):
#Mystery
def bar():
return 5+3
print Foo().bar
Which printed 8. However I cannot remember what the decorator was called. Am I imagining things, or does this exist? And if it does exist what is it called?
You are looking for #property.
You may want to read up on how the #property decorator works.
In short, and as you noted, you can use this to provide dynamically calculated attributes on an object. This is very useful in cases where you may have had code that accessed that as an attribute and you don't necessary want to change this to a function call.
However this by default is read-only. To permit the setting of value to that once more, you can create a setter decorator. Here is an example on how you might use it in the real world which also show you how you can make use of this.

Why does a class get "called" when not initiated? - Python

For example, in the following code:
class test:
print "Hi"
Python would automatically print 'hi'. Sorry if this is an obvious question, but I can't find out why Python would do that unless a 'test' object was initiated.
* I just started programming in general a few months ago and Python is my first language, so please spare some mercy on me.
You are building a class; the body of a class is executed as a function to build the definition. The local namespace of that 'function' forms the set of attributes that make up the class. See the class statement documentation.
Methods in the class body are not executed; like function definitions, you need to call them first. But if you didn't first call the class body, you don't know what methods the class has, at all.
In the same way, any top-level code in a module is executed when you import a module, to form the module namespace. If you put print "Hi" in a module, it is also executed immediately.

Categories