How to check the number of arguments and method from a class has in runtime - python-3.x

Given the class
class TestClassRequiredMethods:
called = False
def publish_db_flaws(self, x):
self.called = True
I'd like to check if the class has a certain method and an expected amount of params.
I solved half of it, now I can check if the object has the attribute but I can't find a way to check how many params are expected in this method.
if not hasattr(publisher, 'publish_db_flaws'):
raise TypeError('The publisher must contain a "publish_db_flaws()" method')
Answer
The accepted answer is working fine for Python 2, if you are working with version 3, you may use:
import inspect
class Publisher:
def publish_db_flaws(self, params_string:str, params_integer:int):
pass
publisher = Publisher()
print(inspect.signature(publisher.publish_db_flaws))
print(inspect.getfullargspec(publisher.publish_db_flaws))
inspect.signature will bring just the signature of the method.
inspect.getfullargspec shows a very complete information about the params.

In addition to hasattr you can use callable(publisher.publish_db_flaws) to check if the attribute is really a callable function.
More detail is available using inspect module as hinted in the comment by ForceBru. inspect.getfullargspec(publisher.publish_db_flaws) gives you information about argument names, if the function uses varargs or keyword args and any defaults.
Similar information is available via inspect.signature. This gives you a Signature object which has a __eq__ method for easy comparison. Note, that this is the preferred method for Python3. getfullargspec is to be used if you need compatibility with the Python2 interface.

Related

Is it possible to overload the return of the type method?

Given the following example:
class Container:
def __init__(self, var):
self.var = var
class Test:
def __init__(self):
self.var = Container("123")
Is it possible to overload the type() method such as type(Test().var) would yield string rather than Container ?
EDIT : I am using the Container class in order to place restrictions on Test.var.
The idea is that Test is a class that contains many variables, some of witch have similar names. The Container class is there to ensure that the right types are used ( __eq__(), __str__(), __add__(), ... are overloaded in order to make the Container class as discreet as possible ) so that issues are diagnosed as fast as possible ( the code will by used by people with a very wide variety of expertise in python )
The other solution would have been to use the #property but as there are many variables, the code ends up being way bigger than it would otherwise and not as simple to maintain ( there is close to a hundred classes witch will have to implement the properties )
I would like to overload type(Test().var) in order to return type(Test().var.var) so that it would be as easy to use as possible
The short answer is "no."
From this official Python doc, it states:
Every object has an identity, a type and a value... The type() function returns an object’s type (which is an object itself). Like its identity, an object’s type is also unchangeable.

Optimization of a simple lazy load for an attribute in Python

This is the property definition I use to lazy load the element attribute of my Element class, borrowed from This post on Python lazy loading.
#property
def element(self):
if not hasattr(self, "_element"):
self._element = self.wait.wait_for_element_to_be_visible(self.locator)
return self._element
It looks for the attribute _element if it doesn't find it then it goes and looks for it. If the attribute is there then it just returns the attribute without looking for it as its already been loaded in.
I've changed the if to be:
if self._element is None:
self._element = self.wait.wait_for_element_to_be_visible(self.locator)
return self._element
Is it more pythonic to see if the attribute exists, or to set _element to None in the __init__ method and then check for that instead?
Doing it the second way also seems better for debugging purposes in IntelliJ as there seems to be a strange loading issue that freezes the tests if I expand my Element object and it starts introspection to display attributes and their values.
My definition of a pythonic solution is the one that's most likely to help a future maintainer understand what's going on when they come across this code (most times it's the same person who wrote it but long after they have it in their memory). Here's some things I might ask myself if I was coming in cold.
1. hasattr
self._element is not in __init__, is this because it's set somewhere else?
Every access checks for the attribute, does that mean it's expecting it to be deleted at some point so it can refresh? Why else is it checked every time?
hasattr will search up the chain of MRO, are we actually looking for something?
2. is None
Found self._element in __init__ being set to None. Am I allowed to set it to None again to get fresh values? The _ in _element is hinting no.
2a. is _Missing
If None is a valid result, use a sentinel instead.
class _Missing:
pass
def __init__():
self._element = _Missing
3. One shot descriptor
Property produces what is known as a data descriptor. It will ignore attributes of the instance and go straight to the classes dictionary (otherwise __set__ won't be able to do it's thing). Here we make our own non-data descriptor (only defines __get__), which won't skip the instances dictionary. This means the instances attribute can be set. Deleting the instance attribute will result in a refreshed value on the next invocation.
class LazyLoadElement:
def __get__(self, instance, owner):
instance.element = instance.wait.wait_for_element_to_be_visible(instance.locator)
return instance.element
class MyClass:
element = LazyLoadElement()
What's the intention of the LazyLoadElement? Name says it all
Can it refresh to another value? Nope, it's set after the first call and removes itself.
Pythonic is a little arm wavy because it needs to make assumptions about who is reading the code at a future date. Out of the 2 original options, number 2 seems most likely to get maintainers up to speed. 3 is my fav though, mainly because once it's loaded there's no more function calls.

NameError, python3 get_step not defined

I'm following the book "Python crash Course" and i keep getting this
NameError: name 'get_step' is not defined
It's in python3 and both files are in the same directory.
So..the function is defined inside this class:
and the class is imported to:
where it calls fill_walks, and fill_walks calls get_step. What am i missing here? can someone help me please
You know how when you refer to x_values, y_values, and num_points, you have to say self.x_values, self.y_values, etc? This is true for all attributes of your instance, including methods. So when you want to do get_step() and get_step is defined on your class, you have to call self.get_step().
In addition, when you define a method on your class, by default it's what's called an instance method, and will automatically be called with the instance as the first argument. You've defined fill_walk correctly, with def fill_walk(self): but get_step is currently not defined properly. You either have to do
def get_step(self):
....
or, since get_step doesn't itself need to access any instance attributes, you can mark it as a static method by defining it like so:
#staticmethod
def get_step():
...
in random_walk.py
change
def get_step():
to
def get_step(self): #<--- self?

Python - GUI checkbox cannot assign the function with arguments to variable

I'm having trouble getting my head around assigning a function to a variable when the function uses arguments. The arguments appear to be required but no matter what arguments I enter it doesn't work.
The scenario is that I'm creating my first GUI which has been designed in QT Designer. I need the checkbox to be ticked before the accept button allows the user to continue.
Currently this is coded to let me know if ticking the checkbox returns anything (which is does) however I don't know how to pass that result onto the next function 'accept_btn'. I thought the easiest way would be to create a variable however it requires positional arguments and that's where I'm stuck.
My code:
class MainWindow(QtWidgets.QMainWindow, Deleter_Main.Ui_MainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.setupUi(self)
self.ConfirmBox.stateChanged.connect(self.confirm_box)
self.Acceptbtn.clicked.connect(self.accept_btn)
def confirm_box(self, state):
if self.ConfirmBox.isChecked():
print("checked")
else:
print("not checked")
checked2 = confirm_box(self, state)
def accept_btn(self):
if checked2 == True:
print("clicked")
else:
print("not clicked")
app = QApplication(sys.argv)
form = MainWindow()
form.show()
app.exec_()
The code gets stuck on 'checked2' with the error:
NameError: name 'self' is not defined
I thought there might be other solutions for running this all within one function but I can't seem to find a way whilst the below is required.
self.ConfirmBox.stateChanged.connect(self.confirm_box)
Would extra appreciate if anyone could help me understand exactly why I need the 'self' argument in the function and variable.
Thanks in advance,
If you just need to enable a button when the checkbox is checked, it can be easily done within the signal connection:
self.ConfirmBox.toggled.connect(self.Acceptbtn.setEnabled)
QWidget.setEnabled requires a bool argument, which is the argument type passed on by the toggled signal, so the connection is very simple in this case.
Apart from this, there are some mistakes in your understanding of classes in Python: it seems like you are thinking in a "procedural" way, which doesn't work well with general PyQt implementations and common python usage, unless you really need some processing to be done when the class is created, for example to define some class attributes or manipulate the way some methods behave. But, even in this case, they will be class attributes, which will be inherited by every new instance.
The line checked2 = confirm_box(self, state) will obviously give you an error, since you are defining checked2 as a class atribute. This means that its value will be processed and assigned when the class is being created: at this point, the instance of the class does not exist yet, Python just executes the code that is not part of the methods until it reaches the end of the class definition (its primary indentation). When it reaches the checked2 line, it will try to call the confirm_box method, but the arguments "self" and "state" do not exist yet, as they have not been defined in the class attributes, hence the NameError exception.
Conceptually, what you have done is something similar to this:
class SomeObject(object):
print(something)
This wouldn't make any sense, since there is no "something" defined anywhere.
self is a python convention used for class methods: it is a keyword commonly used to refer to the instance of a class, you could actually use any valid python keyword at all.
The first argument of any class method is always the reference to the class instance, the only exceptions are classmethod and staticmethod decorators, but that's another story. When you call a method of an instanciated class, the instance object is automatically bound to the first argument of the called method: the self is the instance itself.
For example, you could create a class like this:
class SomeObject(object):
def __init__(Me):
Me.someValue = 0
def setSomeValue(Myself, value):
Myself.someValue = value
def multiplySomeValue(I, multi):
I.setSomeValue(I.someValue * multi)
return I.someValue
But that would be a bit confusing...

Knowing the context/scope at instantiation time

Is there any way to know the context in which an object is instantiated? So far I've been searching and tried inspect module (currentcontext) with poor results.
For example
class Item:
pass
class BagOfItems:
def __init__(self):
item_1 = Item()
item_2 = Item()
item_3 = Item()
I'd want to raise an exception in the instantiation of item_3 (because its outside a BagOfItems), while not doing so in item_1 and item_2. I dont know if a metaclass could be a solution to this, since the problem occurs at instantiation not at declaration.
The holder class (BagOfItems) can't implement the check because when Item intantiation happens outside it there would be no check.
When you instantiate an object with something like Item(), you are basically doing type(Item).__call__(), which will call Item.__new__() and Item.__init__() at some point in the calling sequence. That means that if you browse up the sequence of calls that led to Item.__init__(), you will eventually find code that does not live in Item or in type(Item). Your requirement is that the first such "context" up the stack belong to BagOfItem somehow.
In the general case, you can not determine the class that contains the method responsible for a stack frame1. However, if you make your requirement that you can only instantiate in a class method, you are no longer working with the "general case". The first argument to a method is always an instance of the class. We can therefore move up the stack trace until we find a method call whose first argument is neither an instance of Item nor a subclass of type(Item). If the frame has arguments (i.e., it is not a module or class body), and the first argument is an instance of BagOfItems, proceed. Otherwise, raise an error.
Keep in mind that the non-obvious calls like type(Item).__call__() may not appear in the stack trace at all. I just want to be prepared for them.
The check can be written something like this:
import inspect
def check_context(base, restriction):
it = iter(inspect.stack())
next(it) # Skip this function, jump to caller
for f in it:
args = inspect.getargvalues(f.frame)
self = args.locals[args.args[0]] if args.args else None
# Skip the instantiating calling stack
if self is not None and isinstance(self, (base, type(base))):
continue
if self is None or not isinstance(self, restriction):
raise ValueError('Attempting to instantiate {} outside of {}'.format(base.__name__, restriction.__name__))
break
You can then embed it in Item.__init__:
class Item:
def __init__(self):
check_context(Item, BagOfItems)
print('Made an item')
class BagOfItems:
def __init__(self):
self.items = [Item(), Item()]
boi = BagOfItems()
i = Item()
The result will be:
Made an item
Made an item
Traceback (most recent call last):
...
ValueError: Attempting to instantiate Item outside of BagOfItems
Caveats
All this prevents you from calling methods of one class outside the methods of another class. It will not work properly in a staticmethod or classmethod, or in the module scope. You could probably work around that if you had the motivation. I have already learned more about introspection and stack tracing than I wanted to, so I will call it a day. This should be enough to get you started, or better yet, show you why you should not continue down this path.
The functions used here might be CPython-specific. I really don't know enough about inspection to be able to tell for sure. I did try to stay away from the CPython-specific features as much as I could based on the docs.
References
1. Python: How to retrieve class information from a 'frame' object?
2. How to get value of arguments passed to functions on the stack?
3. Check if a function is a method of some object
4. Get class that defined method
5. Python docs: inspect.getargvalues
6. Python docs: inspect.stack

Resources