How do you check whether a python method is bound or not?
Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?
Asked by: Dominik653 | Posted: 28-01-2022
Answer 1
def isbound(method):
return method.im_self is not None
def instance(bounded_method):
return bounded_method.im_self
When a user-defined method object is created by retrieving a user-defined function object from a class, its
im_self
attribute isNone
and the method object is said to be unbound. When one is created by retrieving a user-defined function object from a class via one of its instances, itsim_self
attribute is the instance, and the method object is said to be bound. In either case, the new method'sim_class
attribute is the class from which the retrieval takes place, and itsim_func
attribute is the original function object.
In Python 2.6 and 3.0:
Answered by: Victoria220 | Posted: 01-03-2022Instance method objects have new attributes for the object and function comprising the method; the new synonym for
im_self
is__self__
, andim_func
is also available as__func__
. The old names are still supported in Python 2.6, but are gone in 3.0.
Answer 2
In python 3 the __self__
attribute is only set on bound methods. It's not set to None
on plain functions (or unbound methods, which are just plain functions in python 3).
Use something like this:
def is_bound(m):
return hasattr(m, '__self__')
Answered by: Oliver858 | Posted: 01-03-2022
Answer 3
The chosen answer is valid in almost all cases. However when checking if a method is bound in a decorator using chosen answer, the check will fail. Consider this example decorator and method:
def my_decorator(*decorator_args, **decorator_kwargs):
def decorate(f):
print(hasattr(f, '__self__'))
@wraps(f)
def wrap(*args, **kwargs):
return f(*args, **kwargs)
return wrap
return decorate
class test_class(object):
@my_decorator()
def test_method(self, *some_params):
pass
The print
statement in decorator will print False
.
In this case I can't find any other way but to check function parameters using their argument names and look for one named self
. This is also not guarantied to work flawlessly because the first argument of a method is not forced to be named self
and can have any other name.
import inspect
def is_bounded(function):
params = inspect.signature(function).parameters
return params.get('self', None) is not None
Answered by: Aida629 | Posted: 01-03-2022
Answer 4
im_self attribute (only Python 2)
Answered by: John495 | Posted: 01-03-2022Answer 5
A solution that works for both Python 2 and 3 is tricky.
Using the package six
, one solution could be:
def is_bound_method(f):
"""Whether f is a bound method"""
try:
return six.get_method_self(f) is not None
except AttributeError:
return False
In Python 2:
- A regular function won't have the
im_self
attribute sosix.get_method_self()
will raise anAttributeError
and this will returnFalse
- An unbound method will have the
im_self
attribute set toNone
so this will returnFalse
- An bound method will have the
im_self
attribute set to non-None
so this will returnTrue
In Python 3:
- A regular function won't have the
__self__
attribute sosix.get_method_self()
will raise anAttributeError
and this will returnFalse
- An unbound method is the same as a regular function so this will return
False
- An bound method will have the
__self__
attribute set (to non-None
) so this will returnTrue
Similar questions
python - How to check if user has been through a method
I am making a simple text-based RPG in Python. Currently I have two methods for most rooms, one for when they first enter and one if they return. Is there a way that I can make sure that they haven't been in that room before without another method?
For example, if I had a method named tomb() i create another method called tombAlready() that contains the same code except for the introductio...
python - Is it possible to check if a value is within a range using count method?
I have a data structure of lists where the format is (<string>, <integer in {1,2,3}>). One string could have different int values associated with it.
Is it possible to use the count function to count the number of elements in the structure that could qualify for the expected int?
For example,
[("y",1), ("y",3), ("n",1), ("y",1)]
python - where to put method that works on a model
I'm working with Django.
I have a model called Agrument. Arguments have sides and owners. I have a function that returns back the side of the most recent argument of a certain user.
like obj.get_current_side(username)
I've added this to the actual Argument model like this
def get_current_side(self, user):
return self.argument_set.latest('pub_date').side
...
python - Getting a dict out of a method?
I'm trying to get a dict out of a method, so far I'm able to get the method name, and its arguments (using the inspect module), the problem I'm facing is that I'd like to have the default arguments too (or the argument type).
This is basically my unit test:
class Test:
def method1(anon_type, array=[], string="string", integer=12, obj=None):
pass
target = {"method1": [
...
python - save method in a view
I have a very simple model:
class Artist(models.Model):
name = models.CharField(max_length=64, unique=False)
band = models.CharField(max_length=64, unique=False)
instrument = models.CharField(max_length=64, unique=False)
def __unicode__ (self):
return self.name
that I'm using as a model form:
from django.forms import ModelForm
from artistmod.artistcat.models import ...
python - Call method from string
If I have a Python class, and would like to call a function from it depending on a variable, how would I do so? I imagined following could do it:
class CallMe: # Class
def App(): # Method one
...
def Foo(): # Method two
...
variable = "App" # Method to call
CallMe.variable() # Calling App()
But it couldn't. Any other way to do this?
python - Why do you need this method inside a Django model?
class mytable(models.Model):
abc = ...
xyz = ...
def __unicode__(self):
Why is the def __unicode__ necessary?
python - Issue in exec method
I am a having two python files file1.py and file2.py.
I am using exec() to get the method/Variables defined in the file2.py.
file1.py have a class as given below
class one:
def __init__(self):
self.HOOK = None
exec(file2.py)
self.HOOK = Generate
### call the hook method ####
self.HOOK()
file2.py looks like as (There is no class define in fi...
python - how can I call view method in different files
If I have one view which called myview1.py and I want to call a view which is located in myview2.py, how can I do that?
should I import myview2.py somehow?
python - Method for dry runs?
at the moment my python code often looks like this:
...
if not dry_run:
result = shutil.copyfile(...)
else:
print " DRY-RUN: shutil.copyfile(...) "
...
I now think about writting something like a dry runner method:
def dry_runner(cmd, dry_run, message, before="", after=""):
if dry_run:
print before + "DRY-RUN: " + message + after
# return execute(...
python - How to call a static method of a class using method name and class name
Starting with a class like this:
class FooClass(object):
@staticmethod
def static_method(x):
print x
normally, I would call the static method of the class with:
FooClass.static_method('bar')
Is it possible to invoke this static method having just the class name and the method name?
class_name = 'FooClass'
method_name = 'sta...
python - Call Class Method From Another Class
Is there a way to call the method of a class from another class? I am looking for something like PHP's call_user_func_array().
Here is what I want to happen:
class A:
def method1(arg1, arg2):
...
class B:
A.method1(1, 2)
python - What's the best Django search app?
How can I use a DLL file from Python?
What is the easiest way to use a DLL file from within Python?
Specifically, how can this be done without writing any additional wrapper C++ code to expose the functionality to Python?
Native Python functionality is strongly preferred over using a third-party library.
python - PubSub lib for c#
Is there a c# library which provides similar functionality to the Python PubSub library? I think it's kind of an Observer Pattern which allows me to subscribe for messages of a given topic instead of using events.
python - What is the best way to copy a list?
This question already has answers here:
python - Possible Google Riddle?
My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant.
t-shirt
So, I have a couple of guesses as to what it means, but I was just wondering if there is something more.
My first guess is that eac...
ssh - How to scp in Python?
What's the most pythonic way to scp a file in Python? The only route I'm aware of is
os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) )
which is a hack, and which doesn't work outside Linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host.
I'm aware of Twisted'...
python - How do I create a new signal in pygtk
I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.
python - What do I need to import to gain access to my models?
I'd like to run a script to populate my database. I'd like to access it through the Django database API.
The only problem is that I don't know what I would need to import to gain access to this.
How can this be achieved?
python - How do I edit and delete data in Django?
I am using django 1.0 and I have created my models using the example in the Django book. I am able to perform the basic function of adding data; now I need a way of retrieving that data, loading it into a form (change_form?! or something), EDIT it and save it back to the DB. Secondly how do I DELETE the data that's in the DB? i.e. search, select and then delete!
Please show me an example of the code ...
python - How do I turn an RSS feed back into RSS?
According to the feedparser documentation, I can turn an RSS feed into a parsed object like this:
import feedparser
d = feedparser.parse('http://feedparser.org/docs/examples/atom10.xml')
but I can't find anything showing how to go the other way; I'd like to be able do manipulate 'd' and then output the result as XM...
Still can't find your answer? Check out these communities...
PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python