1

I constantly see people state that "Everything in Python is an object.", but I haven't seen "thing" actually defined. This saying would lead me to believe that all tokens of any kind are also considered to be objects, including operators, punctuators, whitespace, etc. Is that actually the case? Is there a more concise way of stating what a Python object actually is?

Thanks

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
BenevolentDeity
  • 587
  • 6
  • 15
  • 1
    Sounds like you need to learn some fundamental programming concepts. Have you Googled this at all, or read a book, or taken a course? – TigerhawkT3 Aug 18 '15 at 22:55
  • 3
    uh, uh. slow down with criticism, Tiger. the use of operators, whitespace makes me think the OP does know some programming. – JL Peyret Aug 18 '15 at 22:57
  • Anything which isn't syntax or a keyword is an object. – Peter Wood Aug 18 '15 at 22:59
  • Some reading about SmallTalk would come in handy. SmallTalk defines that "everything". – Eli Korvigo Aug 18 '15 at 23:00
  • Modules are types as well (try `import sys; type(sys)`). Types themselves are objects (`type(int)`, `type(float)`, etc.) Even `type` is an object (of type `type`, in fact.) – chepner Aug 18 '15 at 23:03
  • 1
    possible duplicate of [Is everything an object in python like ruby?](http://stackoverflow.com/questions/865911/is-everything-an-object-in-python-like-ruby) – Peter Wood Aug 18 '15 at 23:06
  • @JLPeyret - I don't think so, as an introductory course for any language that uses objects (C++, Java, Python, etc.) would explain the meaning of "object." Even non-OO languages like C works with values, which are basically "objects." Operators, punctuators, and whitespace are used in mathematics, English (or other languages), and publishing, respectively. – TigerhawkT3 Aug 18 '15 at 23:12
  • @PeterWood uhm, no. By saying "*Anything which isn't syntax or a keyword is an object.*" you're completely mixing up different concepts, the language [grammar](https://docs.python.org/3/reference/grammar.html) and its [data model](https://docs.python.org/3/reference/datamodel.html). The name `foo` can hold a reference to an object. So it's an identifier (grammar) and an object (data model) at the same time, depending on what level of the language you're looking at it. – Lukas Graf Aug 18 '15 at 23:14
  • we'll agree to disagree then, TigerhawkT3. I did not read the OPs question as "what is an object?" I read it specifically as, "I know what an object is, but why are folks saying that pretty much everything in Python is an object?". To take your C++ example, a C++ class, not its instances, is definitely not an object. Coming from that world, Python's underpinning are a quite different, regardless of the language's semantics of object usage. – JL Peyret Aug 19 '15 at 00:01
  • @OP. (you should really put your question clarification in your question, not as an answer). Wouldn't a *struct* be an object by that definition then? Maybe you should also clarify the context of whether you have a particular problem to solve with that info (which would allow more specific examples to be given). Or whether it is "just" intellectual curiosity. – JL Peyret Aug 19 '15 at 00:11
  • @JLPeyret - My question is merely intellectual curiosity so that I can give a meaningful explanation to anyone who might ask me the same question. Merely giving examples of objects does not seem to answer the question of what an object is. – BenevolentDeity Aug 19 '15 at 00:18
  • @TigerhawkT3 - Just FYI, my background consists of 23 years of teaching and using C and C++ and 10 years of using C#. Not much Java, however. – BenevolentDeity Aug 19 '15 at 03:27
  • @LukasGraf *Anything which isn't syntax, or a keyword, is a name, which at runtime will reference an object* Is that better? – Peter Wood Aug 19 '15 at 07:34

5 Answers5

2

Anything that can be assigned to a variable is an object.

That includes functions, classes, and modules, and of course int's, str's, float's, list's, and everything else. It does not include whitespace, punctuation, or operators.

Just to mention it, there is the operator module in the standard library which includes functions that implement operators; those functions are objects. That doesn't mean + or * are objects.

I could go on and on, but this is simple and pretty complete.

Cyphase
  • 11,502
  • 2
  • 31
  • 32
  • I know this isn't the formal definition of the requirements for something being considered a Python object I was looking for, but the first sentence does seem to be a pretty good brute force way to determine if something is an object if you don't already know. – BenevolentDeity Aug 19 '15 at 03:41
  • @BenevolentDeity, I was going to post it with just the first sentence, then added the last sentence, then a bit (relatively lot) more because I thought someone might downvote it for being too short :). – Cyphase Aug 19 '15 at 03:44
2

Some values are obviously objects; they are instances of a class, have attributes, etc.

>>> i = 3
>>> type(i)
<type 'int'>
>>> i.denominator
1

Other values are less obviously objects. Types are objects:

>>> type(int)
<type 'type'>
>>> int.__mul__(3, 5)
15

Even type is an object (of type type, oddly enough):

>>> type(type)
<type 'type'>

Modules are objects:

>>> import sys
>>> type(sys)
<type 'module'>

Built-in functions are objects:

>>> type(sum)
<type 'builtin_function_or_method'>

In short, if you can reference it by name, it's an object.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • 1
    Every function is an object; built-in or not. I would be surprised if this were not the case. – user2864740 Aug 18 '15 at 23:16
  • 1
    I wasn't trying to be exhaustive, although I'm not sure why I singled out built-in functions over user-defined functions. – chepner Aug 19 '15 at 01:17
1

What is generally meant is that most things, for example functions and methods are objects. Modules too. Classes (not just their instances) themselves are objects. and int/float/strings are objects. So, yes, things generally tend to be objects in Python. Cyphase is correct, I just wanted to give some examples of things that might not be immediately obvious as objects.

Being objects then a number of properties are observable on things that you would consider special case, baked-in stuff in other languages. Though __dict__, which allows arbitrary attribute assignment in Python, is often missing on things intended for large volume instantiations like int.

Therefore, at least on pure-Python objects, a lot of magic can happen, from introspection to things like creating a new class on the fly.

Kinda like turtles all the way down.

JL Peyret
  • 10,917
  • 2
  • 54
  • 73
0

You're not going to find a rigorous definition like C++11's, because Python does not have a formal specification like C++11, it has a reference manual like pre-ISO C++. The Data model chapter is as rigorous as it gets:

Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects. (In a sense, and in conformance to Von Neumann’s model of a “stored program computer,” code is also represented by objects.)

Every object has an identity, a type and a value. An object’s identity never changes once it has been created; you may think of it as the object’s address in memory. …

The glossary also has a shorter definition:

Any data with state (attributes or value) and defined behavior (methods).

And it's true that everything in Python has methods and (other) attributes. Even if there are no public methods, there's a set of special methods and values inherited from the object base class, like the __str__ method.


This wasn't true in versions of Python before 2.2, which is part of the reason we have multiple words for nearly the same thing—object, data, value; type, class… But from then on, the following kinds of things are identical:

  • Objects.
  • Things that can be returned or yielded by a function.
  • Things that can be stored in a variable (including a parameter).
  • Things that are instances of type object (usually indirectly, through a subclass or two).
  • Things that can be the value resulting from an expression.
  • Things represented by pointers to PyObject structs in CPython.

… and so on.

That's what "everything is an object" means.

It also means that Python doesn't have "native types" and "class types" like Java, or "value types" and "reference types" like C#; there's only one kind of thing, objects.


This saying would lead me to believe that all tokens of any kind are also considered to be objects, including operators, punctuators, whitespace, etc. Is that actually the case?

No. Those things don't have values, so they're not objects.1


Also, variables are not objects. Unlike C-style variables, Python variables are not memory locations with a type containing a value, they're just names bound to a value in some namespace.2 And that's why you can't pass around references to variables; there is no "thing" to reference.3

Assignment targets are also not objects. They sometimes look a lot like values, and even the core devs sometimes refer to things like the a, b in a, b = 1, 2 loosely as a tuple object—but there is no tuple there.4


There's also a bit of apparent vagueness with things like elements of a numpy.array (or an array.array or ctypes.Structure). When you write a[0] = 3, the 3 object doesn't get stored in the array the way it would with a list. Instead, numpy stores some bytes that Python doesn't even understand, but that it can use to do "the same thing a 3 would do" in array-wide operations, or to make a new copy of the 3 object if you later ask for a[0] = 3.

But if you go back to the definition, it's pretty clear that this "virtual 3" is not an object—while it has a type and value, it does not have an identity.


1. At the meta level, you can write an import hook that can act on imported code as a byte string, a decoded Unicode string, a list of token tuples, an AST node, a code object, or a module, and all of those are objects… But at the "normal" level, from within the code being imported, tokens, etc. are not objects.

2. Under the covers, there's almost always a string object to represent that name, stored in a dict or tuple that represents the namespace, as you can see by calling globals() or dir(self). But that's not what the variable is.

3. A closure cell is sort of a way of representing a reference to a variable, but really, it's the cell itself that's an object, and the variables at different scopes are just a slightly special kind of name for that cell.

4. However, in a[0] = 3, although a[0] isn't a value, a and 0 are, because that assignment is equivalent to the expression a.__setitem__(0, 3), except that it's not an expression.

Community
  • 1
  • 1
abarnert
  • 354,177
  • 51
  • 601
  • 671
0

In the python docs it says:

Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects.

If you start the Python interpreter and type

>>> id(object)
4563621280

it will print an integer that represents its identity, if you do the same thing with another reference name that is not defined, you will get an error

>>> id(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

So by default "object" is defined while "x" is not. But if we define now the "x" object and try again

x = 1
id(x)
4564531496

it will print an integer. Now when you check that the "x" object is an instance of "object" object:

>>> isinstance(x, object)
True

It will print "True". The same for any object, they will be instances of object "object". And if you check the type, you will find that it is a class instance.

>>> type(x)
<class 'int'>

if we check the class 'int' attributes with the builtin function dir it will print

>>> dir(int)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_count', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> dir(x)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_count', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

When you define a class, by default the "object" class is passed to your class so you can inherit from it, for example:

class A:
    pass

is the same as

class A(object):
    pass
>>> class A:
...     pass
...
>>> A.__mro__
(<class '__main__.A'>, <class 'object'>)
>>> class A(object):
...     pass
...
>>> A.__mro__
(<class '__main__.A'>, <class 'object'>)

So, in general, every thing in Python including numbers, strings, etc. They are classes that inherit from the base class "object" which is defined by default at the begining.

object is a base for all classes. It has methods that are common to all instances of Python classes.

Even functions are instances of the class Callable that inherits from the "object" class above. That is one of the reasons why everything in python is considered an object, because you can use all of them as a normal data types that can be stored in a list or passed like arguments to a function and so on. All of this should be correct for Python3.x; in Python2.x classes does not inherit from class "object" by default.

A lot of output, but I hope this will clear a few points, correct me if I have any mistakes. I would also leave this link to pycon video, it is for Michael Foord, I found it useful.

fflores
  • 192
  • 1
  • 6