Elijah Rockers Elijah Rockers - 1 year ago 102
Python Question

Interpreter: Python built-in functions not defined?

I was going through the basics of Python, and testing out some built-in functions in the interpreter. The documentation I was looking at was talking about Python 3... I am using Python 2.7.3.

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

I did some research and it does not seem that
is limited to only Python 3... I also cannot use
even after doing
import math

So why am I seeing an error? Is there some other module I have to import for these functions to work?

Answer Source

isalpha() is not a function but a method of the str type. If you have to, you can extract it as an unbound method and give it a name as a function:

>>> "hello".isalpha()
>>> "31337".isalpha()
>>> isalpha = str.isalpha
>>> isalpha("hello")
>>> isalpha("31337")

Functions in an imported module are members of that module. To pull a function into the main namespace, use the from statement:

>>> import math
>>> math.sin(3.3)
>>> from math import cos
>>> cos(3.3)

Now why does Python work this way? Both the math module and the logging module have a function called log(), but they do very different things.

>>> import math, logging
>>> help(math.log)

    log(x[, base])

    Return the logarithm of x to the given base.
    If the base not specified, returns the natural logarithm (base e) of x.

>>> help(logging.log)

log(level, msg, *args, **kwargs)
    Log 'msg % args' with the integer severity 'level' on the root logger. If
    the logger has no handlers, call basicConfig() to add a console handler
    with a pre-defined format.

If all imported symbols went straight to the main namespace the way they do when you from math import *, a program wouldn't be able to use both modules' log() functions.