3

Is there a way to do something like this:

util.py contains:
def add
def subtract

instantiate.py contains:
def instantiate

where instantiate does:

import util
def instantiate():
    add = util.add
    subtract = util.subtract

So I can skip typing util everytime I use a function and I can instantiate them all using one function?

I tried but I get

NameError: global name 'util' is not defined

3 Answers 3

7

You can import specific functions from a module :

from util import add, substract
Sign up to request clarification or add additional context in comments.

1 Comment

I tried doing: def instanciateAll(): from util import countInstanceOf,getAllUnique,getUnique,flames,reverseWord,fstrip,palindrome But still it says the same error, though I could use what you gave me. I could just save a text file somewhere then add a new function then paste it on the Python cmd. Thanks. :)
4

if you just want to import those functions into the same namespace, you could do something like this:

from util import *

then you can write add and so on without prefixing it with that module

3 Comments

You rock! Thanks that seems to be easier
if you found one of the answers helpful, mark the question as 'answered'
large projects can be a bit harder to read if there are lots of these :-)
0

If you want a method that adds/subtracts, you should use operator.add or operator.sub.

1 Comment

I was just using add and subtract as an example, plus my question is how can I eliminate the assigning of function names to var names so that I will skip using the name of the import when using the functions, thanks anyway! And yeah I know I should use relevant names ^^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.