David542
David542

Reputation: 110083

use raw_input instead of input in python3

I am in the habit of using raw_input(...) for certain debugging. However, in python3 this has changed to input(...). Is there a way to define an alias at the top of my project, such as:

# __init__.py
raw_input = input

I tried the above, but it only worked in the file I added it to, and not any other files in that directory. I'd like this to work basically in every file within my python repository.

Upvotes: 0

Views: 336

Answers (3)

Fake Code Monkey Rashid
Fake Code Monkey Rashid

Reputation: 14537

You can define all aliases in a separate file (e.g. aliases.py) then import said file where needed (i.e. import aliases).

The con with this method that you'll be referencing the alias through aliases.alias unless you make the import stricter (i.e. from aliases import raw_input) or if you don't care about avoiding a wildcard import (i.e. from aliases import *).

Additionally, if you don't mind another import in the aliases file you can use the builtins namespace:

import builtins

builtins.raw_input = input

You still have to define all aliases separate file (e.g. aliases.py) then import said file where needed (i.e. import aliases) but the advantage of using the builtins namespace is that you can use that import exactly as given.

Upvotes: 3

Andrii Maletskyi
Andrii Maletskyi

Reputation: 2232

Put this at the top, and you will get exactly what you want.

import builtins
builtins.raw_input = builtins.input

It is guaranteed to work, but generally considered a bad practice (everybody will be confused with where is that raw_input defined)

Upvotes: 0

Pablo Alvarez
Pablo Alvarez

Reputation: 106

You can do it by creating a module for creating the renaming function and then importing it to every file you want to like this:

First the module function declaration in alias.py

def raw_input(a):
    return input(a)

Secondly, import to another file:

from alias import raw_input
x = raw_input("hello world")
print(x)

Sadly, you will have to make the import of the module to every file you want to use the renamed function.

Hope it works for you!

Upvotes: 0

Related Questions