How to check whether a variable is a class or not?
Even better: use the inspect.isclass
function.
>>> import inspect
>>> class X(object):
... pass
...
>>> inspect.isclass(X)
True
>>> x = X()
>>> isinstance(x, X)
True
>>> inspect.isclass(x)
False
How to check a variable is class object or not
In 2.x, a class object can be be a type
(new-style classes) or a classobj
(classic classes). The type
type is a builtin, but the classobj
type is not. So, how do you get it? That's what the types
module is for.
isinstance(MyClass, (types.TypeType, types.ClassType))
In 3.x, you don't need to worry about classic classes, so:
isinstance(MyClass, type)
Even if you want to compare the types directly, you should never compare any objects by their str
. Compare:
>>> class MyClassicClass:
... pass
>>> str(type(MyClassicClass)) == "<type 'classobj'>"
True
>>> str("<type 'classobj'>") == "<type 'classobj'>"
True
You can almost always just compare objects directly:
>>> type(MyClassicClass) == types.ClassType
True
>>> "<type 'classobj'>" == types.ClassType
False
(And in the incredibly rare cases where you really do need to compare the string representation for some reason, you want the repr
, not the str
.)
Determine if a variable is an instance of any class
I think your understanding of what an instance is wrong here, since everything is an object in python, so 5
is an object of class int
and [2,3]
is an object of class list
and so on.
isinstance(x, y)
is the way to go if you just want to check if x
is an object of y
, but if you want to check if x
is an object of builtin class or your own custom defined class then you should be checking the existence of __dict__
using hasattr(x, '__dict__')
.
How to check if variable is a specific class in python?
Use isinstance
, this will return true even if it is an instance of the subclass:
if isinstance(x, my.object.kind)
Or:
type(x) == my.object.kind #3.x
If you want to test all in the list:
if any(isinstance(x, my.object.kind) for x in alist)
how to check whether a variable is a class or not in c#
In C#, everything that you see is either a class or a struct, (Int is struct for example).
So the question comes down to two things,
Do you want to know all the types which do not have a parameterless constructor (like int doesn't have)
To do that,bool ObjectIsClass(object o)
{
return o.GetType().GetConstructor(new Type[0])!=null;
}Do you want to Look for Primitive types
bool IsPrimitive(object o)
{
return o.GetType().IsPrimitive;
}
how to determine if a variable is a valid class or type in python?
With regards to my comment:
classes and types are all instances of type
, so to speak. That's why this will work:
>>> class foo():
pass
>>> t = foo
>>> t
<class '__main__.foo'>
>>> isinstance(t,type)
True
EDIT - This works for Python3.x
On Python 2.x the class must be a new-style one (i.e. inherit from object
)
class foo(object):
pass
How to check if a variable is an ES6 class declaration?
I'll make it clear up front here, any arbitrary function can be a constructor. If you are distinguishing between "class" and "function", you are making poor API design choices. If you assume something must be a class
for instance, no-one using Babel or Typescript will be be detected as a class
because their code will have been converted to a function instead. It means you are mandating that anyone using your codebase must be running in an ES6 environment in general, so your code will be unusable on older environments.
Your options here are limited to implementation-defined behavior. In ES6, once code is parsed and the syntax is processed, there isn't much class-specific behavior left. All you have is a constructor function. Your best choice is to do
if (typeof Thingy === 'function'){
// It's a function, so it definitely can't be an instance.
} else {
// It could be anything other than a constructor
}
and if someone needs to do a non-constructor function, expose a separate API for that.
Obviously that is not the answer you are looking for, but it's important to make that clear.
As the other answer here mentions, you do have an option because .toString()
on functions is required to return a class declaration, e.g.
class Foo {}
Foo.toString() === "class Foo {}" // true
The key thing, however, is that that only applies if it can. It is 100% spec compliant for an implementation to have
class Foo{}
Foo.toString() === "throw SyntaxError();"
No browsers currently do that, but there are several embedded systems that focus on JS programming for instance, and to preserve memory for your program itself, they discard the source code once it has been parsed, meaning they will have no source code to return from .toString()
and that is allowed.
Similarly, by using .toString()
you are making assumptions about both future-proofing, and general API design. Say you do
const isClass = fn => /^\s*class/.test(fn.toString());
because this relies on string representations, it could easily break.
Take decorators for example:
@decorator class Foo {}
Foo.toString() == ???
Does the .toString()
of this include the decorator? What if the decorator itself returns a function
instead of a class?
What's the best way to check if class instance variable is set in Python?
You've forgotten the EAFP principle:
try:
value = self.__var
except AttributeError:
# do something else
If you're determined to use a sentinel, you can combine it with a class variable:
class EC():
__var = object():
...
if self.__var is not EC.__var:
...
Checking if a variable belongs to a class in python
You could use the __dict__
property which composes a class, for example:
In [1]: class Foo(object):
...: bar = "b"
...: zulu = "z"
...:
In [2]: "bar" in Foo.__dict__
Out[2]: True
Or as you're searching for the values use __dict__.values()
:
In [3]: "b" in Foo.__dict__.values()
Out[3]: True
As Peter Wood points out, the vars()
built-in can also be used to retrieve the __dict__
:
In [12]: "b" in vars(Foo).values()
Out[12]: True
The __dict__
property is used as a namespace for classes and so will return all methods, magic methods and private properties on the class as well, so for robustness you might want to modify your search slightly to compensate.
In your case, you might want to use a classmethod
, such as:
class States(object):
ALABAMA = "AL"
FLORIDA = "FL"
@classmethod
def is_state(cls, to_find):
print(vars(cls))
states = [val for key, val in vars(cls).items()
if not key.startswith("__")
and isinstance(val, str)]
return to_find in states
States.is_state("AL") # True
States.is_state("FL") # True
States.is_state("is_state") # False
States.is_state("__module__") # False
Update
This clearly answer's the OPs question, but readers may also be interested in the Enum
library in Python 3, which would quite possibly be a better container for data such as this.
Related Topics
How to Find Unused Functions in Python Code
How to Get All of the Output from My .Exe Using Subprocess and Popen
Matplotlib - Add Colorbar to a Sequence of Line Plots
Selecting Pandas Column by Location
Type Hints with User Defined Classes
Python's in (_Contains_) Operator Returns a Bool Whose Value Is Neither True Nor False
Python: Random Selection Per Group
How to Use Append with Pickle in Python
Python: Nameerror: Global Name 'Foobar' Is Not Defined
I am Sending Commands Through Serial Port in Python But They Are Sent Multiple Times Instead of One
Python Re.Sub Back Reference Not Back Referencing
How to Trace the Path in a Breadth-First Search
Why Doesn't Django's Model.Save() Call Full_Clean()