@PyNoobs: The Fundamental Five Built-in Functions, and Beyond!

R

rantingrick

============================================================
The "Fundamental Five" built-in functions
============================================================
There are quite a few helpful built in functions provided to the
python programmer however in my mind five of them are the most
important to Python noobs. The "fundamental five" i call them. I
believe you should not do anything with Python until you are
completely familier with these five because most of the bugs and mis-
understanding a new user experiences can be solved by using these five
functions.
============================================================

--------------------------------------------------
1. help()
--------------------------------------------------
http://docs.python.org/py3k/library/functions.html#help

The "help" function is by far the most important of all Python built
in functions. It is a gift handed down from the gods who reside at py-
dev so don't balk at it or you'll suffer plagues of exceptions. Unlike
other languages, Python has documentation built-in in the form of
docstrings and the help function will pull out as much or as little
info as you'd like from these do strings. No need to carry around
heavy books or hundreds of links to www tuts because everything you
need to know (reference wise) is available via the help function. Run
the help function and ye shall be enlightened!

--------------------------------------------------
2. dir()
--------------------------------------------------
http://docs.python.org/py3k/library/functions.html#dir

Python has name spaces. Name spaces are awesome. Name spaces keep code
from clashing with other code. The dir() function will list the
currently defined names in the current namespace. If your getting
NameErrors check the name space with dir() function.

--------------------------------------------------
3. repr()
--------------------------------------------------
http://docs.python.org/py3k/library/functions.html#repr

Most new user think that printing an object to stdout is all they'll
ever need. However when you call print -- or sys.stdout.write(object)
-- you are only seeing a "friendly" version of the object. You can
even control the return value in your own classes bu overriding the
obj.__str__() special method. This friendly version is sufficient most
of the time HOWEVER when debugging it can lead you to smash you head
on the keyboard repeatedly due to it's sometimes misleading nature. If
you need to get the true "representation" of an object then call...
repr(object).

--------------------------------------------------
4. type()
--------------------------------------------------
http://docs.python.org/py3k/library/functions.html#isinstance

Ever had a TypeError? Ever had some object you were just sure was one
type but is not behaving like that type? Then check it's type for
Pete's sake! Even experienced programmers (of many languages) suffer
from TypeErrors (be them subtle or not) because the type of an object
cannot be inferred simply by looking at it's identifier. So when
something ain't right, skip the tripe, and check the type!

--------------------------------------------------
5. id()
--------------------------------------------------
http://docs.python.org/py3k/library/functions.html#id

Ah yes, another source of frustration is the old "identical twin"
syndrome (or in the worst forms; multiplicity syndrome!). Yes, on the
surface that list of lists looks as if it contains unique elements
HOWEVER you keep getting strange results. How are you going to find
the problem? Hmm? Never fear my confused new friend, by comparing the
ids of two objects you can know if they are actually the same or
different. If the id is the same, the objects are the same.

--------------------------------------------------
Summary
--------------------------------------------------
These five functions are vital to debugging any python code or
understanding an API. You will be using these functions over and over
again, so the sooner you learn them the better!

==================================================
Extending "The Five"
==================================================
Once you have mastered the five it is time to expand your horizons a
bit. The next group of functions will complete the circle of
introspection.
==================================================
* hasattr()
* isintance()
* issubclass()
* callable()
* super()
* vars()
* globals()
* locals()

* ascii()

==================================================
General Built-in Functions by Group.
==================================================

--------------------------------------------------
Objects
--------------------------------------------------
Bulling an object:
* delattr()
* getattr()
* setattr()

Setting the rules:
* staticmethod()
* classmethod()
* property()

--------------------------------------------------
Numbers and Math
--------------------------------------------------
* abs()
* divmod()
* round()
* pow() # use ** or math.pow()

--------------------------------------------------
List / Collection Types:
--------------------------------------------------
* len()
* min()
* max()
* any()
* all()
* sum()

Ordering:
* sorted()
* slice() # Use list[start:stop].
* reversed()
* enumerate()
* zip()

Functional:
* filter()
* map()

Iteration:
* iter()
* next()

--------------------------------------------------
Input / Output:
--------------------------------------------------
* input()
* open()
* print()
* format()

--------------------------------------------------
Casting and Creating:
--------------------------------------------------
str(), int(), chr(), float(), oct(), ord(), complex(), hex(), bin(),
bool(),

tuple(), list(), range(), dict(), frozenset(), bytes(), bytearray(),
set(), hash(), memoryview(), object()
 
T

Thomas Jollans

Beyond!


Pro tip: the "IPython" enhanced Python shell makes these two even more
amicable.
--------------------------------------------------
3. repr()
--------------------------------------------------
http://docs.python.org/py3k/library/functions.html#repr

Most new user think that printing an object to stdout is all they'll
ever need.

Also handy: the "pprint" stdlib module to pretty-print complex structures.

http://docs.python.org/py3k/library/pprint.html

This reminds me of something I did last year. Some of you might recall.
http://blog.jollybox.de/archives/62-python-swap
(Word of warning: bad idea. Very, very bad idea. Still, potentially
amusing. Kind of like blowing up a giant hydrogen-filled baloon.)
 
S

Steven D'Aprano

============================================================
The "Fundamental Five" built-in functions
============================================================
There are quite a few helpful built in functions provided to the
python programmer however in my mind five of them are the most
important to Python noobs. The "fundamental five" i call them. I
believe you should not do anything with Python until you are
completely familier with these five because most of the bugs and mis-
understanding a new user experiences can be solved by using these five
functions.

Rick, this is excellent work. If you did more of this sort of thing and less
ranting, you would be far more respected and much less likely to be
kill-filed.

You've just earned yourself a retroactive Get Out Of Kill-File card. Don't
make me regret it.
 
T

Terry Reedy

============================================================
The "Fundamental Five" built-in functions
============================================================
There are quite a few helpful built in functions provided to the
python programmer however in my mind five of them are the most
important to Python noobs. The "fundamental five" i call them. I
believe you should not do anything with Python until you are
completely familier with these five because most of the bugs and mis-
understanding a new user experiences can be solved by using these five
functions.
============================================================

help() with no args puts one into a special help mode to get info on
various topics. help(obj) gets help on that object. I do not do the
former much, but I increasingly use the latter.

--------------------------------------------------
2. dir()
--------------------------------------------------
http://docs.python.org/py3k/library/functions.html#dir

Python has name spaces. Name spaces are awesome. Name spaces keep code
from clashing with other code. The dir() function will list the
currently defined names in the current namespace. If your getting
NameErrors check the name space with dir() function.

I use this constantly.
--------------------------------------------------
3. repr()
--------------------------------------------------
http://docs.python.org/py3k/library/functions.html#repr

Most new user think that printing an object to stdout is all they'll
ever need. However when you call print -- or sys.stdout.write(object)
-- you are only seeing a "friendly" version of the object.

This mostly applies to strings, which *do* have 2 printed versions. It
is occasionally very important for debugging string problems.

Printing collections alreays used repr() for members of the collection.
--------------------------------------------------
4. type()
--------------------------------------------------
http://docs.python.org/py3k/library/functions.html#isinstance

Ever had a TypeError? Ever had some object you were just sure was one
type but is not behaving like that type? Then check it's type for
Pete's sake! Even experienced programmers (of many languages) suffer
from TypeErrors (be them subtle or not) because the type of an object
cannot be inferred simply by looking at it's identifier. So when
something ain't right, skip the tripe, and check the type!

--------------------------------------------------
5. id()
--------------------------------------------------
http://docs.python.org/py3k/library/functions.html#id

Ah yes, another source of frustration is the old "identical twin"
syndrome (or in the worst forms; multiplicity syndrome!). Yes, on the
surface that list of lists looks as if it contains unique elements
HOWEVER you keep getting strange results. How are you going to find
the problem? Hmm? Never fear my confused new friend, by comparing the
ids of two objects you can know if they are actually the same or
different. If the id is the same, the objects are the same.

This is the most dangerous of the builtins, as it sometimes mislead
newbies into 'discovering' non-existent 'bugs'. The main point is that
the id of immutable objects is mostly an irrelevant implementation
detail, while the id of mutables may be critical. Lists of lists is a
particular area where id() is really useful.
 
R

rantingrick

This mostly applies to strings, which *do* have 2 printed versions.  It
is occasionally very important for debugging string problems.

Actually you have to be careful of objects too. Consider this:

py> import Tkinter
py> root = Tkinter.Tk()
py> print root
..
py> print repr(root)
<Tkinter.Tk instance at 0x02BDC4E0>
py> label = Tkinter.Label(root)
py> print label
..46012656
py> print repr(label)
<Tkinter.Label instance at 0x02BE18F0>

....as you can see, if someone overrides __str__ you can get some very
confusing return values from a naked print(obj) -- which simply calls
"obj.__str__()" under the covers.
This is the most dangerous of the builtins, as it sometimes mislead
newbies into 'discovering' non-existent 'bugs'. The main point is that
the id of immutable objects is mostly an irrelevant implementation
detail, while the id of mutables may be critical. Lists of lists is a
particular area where id() is really useful.

Yes this one can cause some major confusion to newcomers. I wonder if
python should throw a warning anytime you call id() on an immutable
type.

py> a = "12345"
py> id(a)
45313728
py> b = "12345"
py> id(b)
45313728

That first call to id should have thrown a warning:

Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
id(a)
Warning: Comparing ids of immutable types is unreliable!

and an Exception if someone tries an assertion!

py> assert id(a) != id(b)

Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
assert id(a) != id(b)
Exception: Cannot compare immutable types!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top