Elijah Rockers - 3 months ago 13x

Python Question

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

'32456'

>>> 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

`isalpha()`

`sin(3.3)`

`import math`

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

Answer

`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()
True
>>> "31337".isalpha()
False
>>> isalpha = str.isalpha
>>> isalpha("hello")
True
>>> isalpha("31337")
False
```

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)
-0.1577456941432482
>>> from math import cos
>>> cos(3.3)
-0.9874797699088649
```

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(...)
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.

Source (Stackoverflow)

Comments