hhblackno
hhblackno

Reputation: 17

Python's help function executes another program "string.py"

I've been messing around with python a little bit and have created a program saved as string.py where I tested out some string functions. In another program function.py in the same directory I wrote this code

def say_hi(first = 'John', last = 'Doe'):
    """Say hello."""
    print('Hi {} {}!'.format(first, last))

help(say_hi)

which, however, executed the string.py program. I found out after some testing that renaming string.py to anything else solves the problem and the function.py program is executed as intended, but I'd like to understand why the help function executed the other program in the first place.

Upvotes: 0

Views: 43

Answers (1)

Random Davis
Random Davis

Reputation: 6857

You are shadowing the name string, which is a built-in module: https://docs.python.org/3/library/string.html

string is a commonly used module. Lots of built-in functions in python run scripts that have import string in them, meaning it'll import your string.py and not the built-in one.

This is just yet another example of why it's a bad idea to name scripts or variables with names that already exist in standard Python.

Upvotes: 3

Related Questions