Let's say I want to rename a function like "print" into "bark". Is there a way to do that?
I found information on how to apply another name to a library, but that's it. And don't ask about the question, the "bark" idea is just an example. I remember you can do something like that in C# and wonder if Python is an exception.
You can change the "name" of the function assigning it to an other variable, since in Python functions are objects.
>>> def foo(): pass
>>> foo
<function foo at 0x0000021C6B537E20>
>>> bar = foo
>>> bar
<function foo at 0x0000021C6B537E20> # Functions gets named with the name given by def, so assigning it to bar doesn't really change its name
So you just have to do this:
bar = foo # That's it
If you have the doubt that this may be a non-working way in some language, why don't you simply try? Open your Python Launcher, then insert this commands:
>>> myFunction = quit
>>> myFunction()
If the window collapses then you have the prove that this works with Python.
I found information on how to apply another name to a library
Yes, in this case you would have to do this:
from myModule import foo as bar
You can just write
bark = print
bark('Hello World')
My_Module=input()
My_Method=input()
from My_Module import My_Method
I'm writing a program and I need to import a method first.
But when I type what I did in above it sends an error and says can't "import name My_Method from My_Module".
I tried 2 other different codes but they didn't work either.I know that My_Method is a name and can't be imported but what can I do to solve this problem and have it worked?
You need to use __import__ to get the module in a dynamic way (using a variable content as name)
Then, you need to use getattr to get the function within the module.
import importlib
modulename = input('module ')
funcname = input('func ')
mod = importlib.import_module(modulename)
func = getattr(mod, funcname)
print(func)
# call the function
func()
Thx to Patrick Haugh and his comment
I have a Python file with two functions in it:
== bar.py ==
def foo1(): pass
def foo2(): pass
== EOF ==
And then I import it into the global namespace like so:
from bar import *
So both functions foo1 and foo2 should be available to me. If I try to print each one:
print(foo1)
then the interpreter happily tells me it's there:
<function foo1 at 0x7fd6e489fcf8>
But then I try to print the second one:
print(foo2)
And I get the error:
NameError: name 'foo2' is not defined
What are some possible causes of this? Could this be, for example, if foo1 was written in Python 3 syntax and foo2 was written in Python 2 syntax? What else could it be?
NOTE: thanks to this question, which I used for formatting this question.
EDIT: Here's another version of bar.py, as requested in a comment:
def foo1():
pass
def foo2():
pass
This might occur if another version of bar.py exists in a filesystem path that is listed in your PYTHONPATH before the bar.py you are actually editing. The python interpreter will use the first bar.py it finds in the python path, after the current working folder of course.
I have two files. One is program_utils.py with the contents:
class SomeException(Exception):
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
another, say, program.py, with
import program_utils
def SomeFunction(arg):
if arg in set([ok_val1, ok_val2]):
# do something
else:
raise SomeException('reason')
When I run program.py it complains: NameError: name 'MyException' is not defined. When I paste the contents of program_utils.py directly into program.py, it works fine. Why?
Unlike #include in C/C++, in python the import statement is not equivalent to copy/pasting the file into your file.
If you want that behavior, you can sort of get it by doing:
from program_utils import *
However, there are some caveats. e.g.: if you are importing a package, the __all__ variable in the __init__.py controls which symbols get imported whtin doing from foo import *.
In general, from foo import * is not a very good practice. You don't necessarily know what symbols you are importing. Additionally you may overwrite the value of some symbols if you do that with more than one module and they both define the same symbol(s).
Arguably it is also somewhat more clear what is going on if you use the module name when using its symbols. i.e.:
foo.bar()
vs
from foo import *
...
from spam import *
bar()
In the second case it might not be obvious that bar came from the foo module.
There is a (small) performance consideration. If you end up doing foo.bar() a lot, you are actually doing an unnecessary dictionary lookup because every time, the interpreter looks up 'bar' in foo.__dict__. To fix that, you can do:
from foo import bar
I am currently doing a python tutorial, but they use IDLE, and I opted to use the interpreter on terminal. So I had to find out how to import a module I created. At first I tried
import my_file
then I tried calling the function inside the module by itself, and it failed. I looked around and doing
my_file.function
works. I am very confused why this needs to be done if it was imported. Also, is there a way around it so that I can just call the function? Can anyone point me in the right direction. Thanks in advance.
If you wanted to use my_file.function by just calling function, try using the from keyword.
Instead of import my_file try from my_file import *.
You can also do this to only import parts of a module like so :
from my_file import function1, function2, class1
To avoid clashes in names, you can import things with a different name:
from my_file import function as awesomePythonFunction
EDIT:
Be careful with this, if you import two modules (myfile, myfile2) that both have the same function inside, function will will point to the function in whatever module you imported last. This could make interesting things happen if you are unaware of it.
This is a central concept to python. It uses namespaces (see the last line of import this). The idea is that with thousands of people writing many different modules, the likelihood of a name collision is reasonably high. For example, I write module foo which provides function baz and Joe Smith writes module bar which provides a function baz. My baz is not the same as Joe Smiths, so in order to differentiate the two, we put them in a namespace (foo and bar) so mine can be called by foo.baz() and Joe's can be called by bar.baz().
Of course, typing foo.baz() all the time gets annoying if you just want baz() and are sure that none of your other modules imported will provide any problems... That is why python provides the from foo import * syntax, or even from foo import baz to only import the function/object/constant baz (as others have already noted).
Note that things can get even more complex:
Assume you have a module foo which provides function bar and baz, below are a few ways to import and then call the functions contained inside foo...
import foo # >>> foo.bar();foo.baz()
import foo as bar # >>> bar.bar();bar.baz()
from foo import bar,baz # >>> bar(); baz()
from foo import * # >>> bar(); baz()
from foo import bar as cow # >>> cow() # This calls bar(), baz() is not available
...
A basic import statement is an assignment of the module object (everything's an object in Python) to the specified name. I mean this literally: you can use an import anywhere in your program you can assign a value to a variable, because they're the same thing. Behind the scenes, Python is calling a built-in function called __import__() to do the import, then returning the result and assigning it to the variable name you provided.
import foo
means "import module foo and assign it the name foo in my namespace. This is the same as:
foo = __import__("foo")
Similarly, you can do:
import foo as f
which means "import module foo and assign it the name f in my namespace." This is the same as:
f = __import__("foo")
Since in this case, you have only a reference to the module object, referring to things contained by the module requires attribute access: foo.bar etc.
You can also do from foo import bar. This creates a variable named bar in your namespace that points to the bar function in the foo module. It's syntactic sugar for:
bar = __import__("foo").bar
I don't really understand your confusion. You've imported the name my_file, not anything underneath it, so that's how you reference it.
If you want to import functions or classes inside a module directly, you can use:
from my_file import function
I'm going to incorporate many of the comments already posted.
To have access to function without having to refer to the module my_file, you can do one of the following:
from my_file import function
or
from my_file import *
For a more in-depth description of how modules work, I would refer to the documentation on python modules.
The first is the preferred solution, and the second is not recommended for many reasons:
It pollutes your namespace
It is not a good practice for maintainability (it becomes more difficult to find where specific names reside.
You typically don't know exactly what is imported
You can't use tools such as pyflakes to statically detect errors in your code
Python imports work differently than the #includes/imports in a static language like C or Java, in that python executes the statements in a module. Thus if two modules need to import a specific name (or *) out of each other, you can run into circular referencing problems, such as an ImportError when importing a specific name, or simply not getting the expected names defined (in the case you from ... import *). When you don't request specific names, you don't run into the, risk of having circular references, as long as the name is defined by the time you actually want to use it.
The from ... import * also doesn't guarantee you get everything. As stated in the documentation on python modules, a module can defined the __all__ name, and cause from ... import * statements to miss importing all of the subpackages, except those listed by __all__.