0

I'm newbie in python.
As I learned, str(123) returns the string format of value 123 which is '123' but what if we have a variable named str, how can I call the str function?

In[2]: str(123)
Out[2]: '123'
In[3]: str='hello world'
In[4]: str(123)
Traceback (most recent call last):
  File "/Users/x625/anaconda/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2885, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-4-6d97c31da288>", line 1, in <module>
    str(123)
TypeError: 'str' object is not callable

How can I call str() function again?

2
  • Don't use str as a variable. However, you can still get to it using import builtins and then builtins.str. Commented Aug 7, 2016 at 17:51
  • del str to be able to call it again. Fun fact this method of shadowing is used in security to prevent usage of harmful functions such as eval. Commented Apr 28 at 13:25

3 Answers 3

2

You still can access it:

import builtins
builtins.str(123)

Don't use str as a variable name, it is a keyword.

Sign up to request clarification or add additional context in comments.

2 Comments

This doesn't work in interactive mode or from __main__. If you really want to use the module that contains all built-in names, that's import __builtin__ (no s) on Python 2, or import builtins on Python 3.
edit my answer please or post a better one
1

Just don't call your variables str.

If you made a mistake in interactive mode and need to get rid of a variable you picked a bad name for, you can do del str, but don't do that in an actual program.

3 Comments

Thank you for your advise, so you mean there is no way around that to call actual function name rather than variable if we use function as a variable name?
@user3375740: This isn't C#. Functions and variables don't live in separate namespaces. There are technically workarounds for calling a built-in when you have a variable shadowing it, but they're far clumsier than just picking a different name.
there is a way to access builtin functions using globals() or using builtins
1

Your variable name str='hello world' collides withe the function str.

Just pick another name to your variable.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.