Omer Bromberg
Omer Bromberg

Reputation: 17

Python how remove the name of the parent object from function names

I have a .py file with my own functions, which I run on ipython on several machines. The problem is that in some platforms I can call functions like sin(), size(), plot() without the prefix of the parent class name and on other platforms I need to write the full path: numpy.sin(), ndarray.size(), pyplot.plot(). 1) What are the rules that determine when the full path is used and when I can use the short form? 2) Can I manually set a function to its short form?

Upvotes: 0

Views: 242

Answers (3)

PM 2Ring
PM 2Ring

Reputation: 55489

The way you call functions imported from other modules depends on how you do your imports.

If you do

import numpy

then you call the numpy module's sin function like this:

numpy.sin()

If you get sick of typing "numpy" all the time, you can do this:

import numpy as np
np.sin()

You can do

from numpy import sin, cos
sin()
cos()

But that clutters up your namespace with the imported names.

You can even do

from numpy import *

but that style is extremely discouraged, since it dumps all of the numpy names into your namespace. And if you do such "star" imports with multiple modules then if there are any duplicated names the later imports will clobber the names of the earlier imports. Please see Why is “import *” bad? for various opinions on this topic.

My preference is to use the full module name for things that I don't mention often in my code and to use a short name (as in my 2nd example) for things that are used more frequently. The from modulename import thing form is handy in short scripts, but it becomes unwieldy in larger programs, especially if you're importing things in that fashion from multiple modules.

Note that you can always assign a function to a short name by a simple assignment statement

s = numpy.sin

This can be useful to make a local reference inside a function, since looking up such a reference is faster than looking up the global reference.

Upvotes: 1

Srgrn
Srgrn

Reputation: 1825

Basically there are rules governing the import statement stated in https://docs.python.org/3/reference/import.html

however in this specific case and without seeing the code i would guess that importing using from something import somethingelse will import the functions so they will be available without the explicit module call.

you can also do from something import * will import all functions.

Upvotes: 0

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17424

Take a look at the definition of the import statement. There are two forms:

import math
math.sin(1)

Second form is:

from math import sin
sin(1)

Note that since modules are also objects, you can also store math.sin in the first case in a local variable:

import math
sin = math.sin
sin(1)

Upvotes: 1

Related Questions