How to use an import to only one function? - python

How can I import a module in Python, but only to one function?
My imagination:
def func():
localize from myModule import helperFunc # localize means "to this scope only: "
helperFunc("do something magical") # but it doesn't exist
try:
helperFunc("do something magical")
except NameError:
print("'helperFunc' doesn't exist at this scope") # this would get run
The problem here is that localize doesn't exist. Is there something in Python to simulate that?

You can just import modules normally:
def choose5(lst):
from random import choices
# choices is imported here
return choices(lst, k=5)
print(choose5([1, 2, 3]))
# choices is not imported here

def my_now():
from datetime import datetime
return datetime.now()
try:
print("Success", datetime.now())
except NameError:
print("NameError occurred", my_now())
Running the above code will give you the output
NameError occurred 2020-11-06 21:20:19.930863
datetime was scoped to the my_now function. Trying to calling datetime.now() directly failed, so the function my_now was called and that was able to call datetime.now() successfully.

Related

Can't import functions/modules

I'm simply trying to import a function from another script. But despite import running successfully, the functions never enter my local environment.
The paths and files look like this:
project/__main__.py
project/script_a.py
from setup import script_b
x = ABC() # NameError: name 'ABC' is not defined
print(x)
project/setup/__init__.py
project/setup/script_b.py
def ABC():
return "ABC"
I've done this before and the documentation (officials and on here) is quite straightforward but I cannot grasp what I am failing to understand. Is the function running but never entering my environment?
I also tried using...
if __name__ == '__main__':
def ABC():
return "ABC"
...as script_b.
Import the functions inside the module:
from setup.script_b import ABC
Or call the function on the modules name like said in the comments
x = script_b.ABC()

Python Creating and Importing Modules

I wrote functions that are applyRules(ch), processString(Oldstr) and named it lsystems.py
And I put
import lsystems
def main():
inst = applyRules("F")
print(inst)
main()
and saved it as mainfunctioni
However, when I try to run mainfunctioni, it says 'applyRules' is not defined.
Doesn't it work because I put import lsystems?
What should I do to work my mainfunctioni through lsystems?
You have to call it with module.function() format. So in this case, it should be called like as follows:
inst = lsystems.applyRules("F")
You have to access all the methods from your module with the same format. For processString(Oldstr), it should be similar.
test_string = lsystems.processString("Somestring")
When you import a module using import <module> syntax, you need to access the module's contents through its namespace, like so:
import lsystems
def main():
inst = lsystems.applyRules("F")
print(inst)
main()
Alternatively, you can directly import the function from the module:
from lsystems import applyRules
def main():
inst = applyRules("F")
print(inst)
main()

Getting error for datetime in python

I have a file named global.py and a function to create report :
import datetime
class customFail(Exception):pass
def createReport(myModule,iOSDevice,iOSVersion):
now=datetime.datetime.now()
resultPath="../Results"
resultFile="Result_%d_%d_%d_%d_%d_%d.html" % (now.day,now.month,now.year,now.hour,now.minute,now.second)
fileName="%s/%s" % (resultPath,resultFile)
fNameObj=open("../Results/resfileName.txt","w") #Writing result filename temporary
fNameObj.write(fileName) #in a file to access this filename by other functions (rePass,resFail)
fileObj=open(fileName,"w")
fileObj.write("<html>")
fileObj.write("<body bgcolor=\"Azure\">")
fileObj.write("<p> </p>")
fileObj.write("<table width=\"600\" border=\"5\">");
fileObj.write("<tr style=\"background-color:LemonChiffon;\">")
fileObj.write("<td width=\"40%\"><b>Module : </b>"+ myModule+"</td>")
fileObj.write("<td width=\"30%\"><b>Time : </b>"+ now.strftime("%d-%m-%Y %H:%M")+"</td>")
fileObj.write("</tr>")
fileObj.write("<tr>")
fileObj.write("</tr>")
fileObj.write("</table>")
fileObj.write("<table width=\"600\" border=\"5\">");
fileObj.write("<tr style=\"background-color:BurlyWood;\">")
fileObj.write("<td width=\"70%\"><b>Device : </b>"+ iOSDevice+" - <b> Version : </b>"+ iOSVersion+"</td>")
fileObj.write("</tr>")
fileObj.write("</table>")
#fileObj.write("<br>")
and a script file where i call this function called scripts.py
import os
from selenium import webdriver
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.common.action_chains import ActionChains
import time
import sys
sys.path.append('/Users/admin/Desktop/_Suite/Global Scripts/')
from funcLib import *
from myGlobal import *
wd = deviceSelection();
iOSVersion="i7"
iOSDevice="iPhone"
modName="BAT"
suiteStartTime=0
def main():
start()
fntesttrial();
finish();
def start():
global modName,suiteStartTime
global appName,ctx_app,ctx_simulator
suiteStartTime=time.time();
createReport(modName,iOSDevice,iOSVersion)
stts=api_clr_acnt.fnClearAccount(myDict["UserName"],myDict["Password"],myDict["Environment"])
def fntesttrial():
try:
wd.find_element_by_name("Accept").click()
time.sleep(5)
wd.find_element_by_name("Sign In").click()
time.sleep(5)
wd.find_element_by_name("Need help?").click()
time.sleep(5)
wd.find_element_by_name("Close").click()
time.sleep(5)
finally:
wd.quit()
main()
When I run this i am getting error like :
now=datetime.datetime.now()
NameError: global name 'datetime' is not defined
I am not understanding why I am getting that error. Please help me since i am new to python.
I think you need to import datetime at the top of the script file (code block 2). It gives you the error because datetime is indeed undefined in the script, as it hasn't been imported yet.
When you call "createReport()", "now" can't be defined, as it calls on the datetime module, which isn't imported.
If you wanted, you could write import datetime at the start of the method definition, but if you called the method twice, it would import datetime twice, so you're probably better off just importing it at the start of the second codeblock.

import file by url route python

Im trying to import files on Flask app in base of url route. I started to coding python few days ago so i havent idea if i doing it well. I write this on :
#app.route('/<file>')
def call(file):
__import__('controller.'+file)
hello = Example('Hello world')
return hello.msg
And i have other file called example.py into a controller folder that contains this:
class Example:
def __init__(self, msg):
self.msg = msg
So i start from terminal the app and i try to enter to localhost:5000/example.
Im trying to show in screen Hello world but give me the next error:
NameError: global name 'Example' is not defined
Thanks for all!
__import__ returns the newly imported module; names from that module are not added to your globals, so you need to get the Example class as an attribute from the returned module:
module = __import__('controller.'+file)
hello = module.Example('Hello world')
__import__ is rather low-level, you probably want to use importlib.import_module() instead:
import importlib
module = importlib.import_module('controller.'+file)
hello = module.Example('Hello world')
If you need to dynamically get the classname too, use getattr():
class_name = 'Example'
hello_class = getattr(module, class_name)
hello = hello_class('Hello world')
The Werkzeug package (used by Flask) offers a helpful functions here: werkzeug.utils.import_string() imports an object dynamically:
from werkzeug.utils import import_string
object_name = 'controller.{}:Example'.format(file)
hello_class = import_string(object_name)
This encapsulates the above process.
You'll need to be extremely careful with accepting names from web requests and using those as module names. Please do sanitise the file argument and only allow alphanumerics to prevent relative imports from being used.
You could use the werkzeug.utils.find_modules() function to limit the possible values for file here:
from werkzeug.utils import find_modules, import_string
module_name = 'controller.{}'.format(file)
if module_name not in set(find_modules('controller')):
abort(404) # no such module in the controller package
hello_class = import_string(module_name + ':Example')
I think you might not add the directory to the file, add the following code into the previous python program
# Add another directory
import sys
sys.path.insert(0, '/your_directory')
from Example import Example
There are two ways for you to do imports in Python:
import example
e = example.Example('hello world')
or
from example import Example
e = Example('hello world')

Running a function in Python if a user chooses it (EasyGui)

I'm using EasyGui to allow a user to select multiple options. Each option is a function which they can run if they select it. I'm trying to use dictionaries as suggested in other threads but I'm having trouble implementing it (Module object is not callable error). Is there something I'm missing?
from easygui import *
import emdtest1
import emdtest2
import emdtest3
EMDTestsDict = {"emdtest1":emdtest1,
"emdtest2":emdtest2,
"emdtest3":emdtest3}
def main():
test_list = UserSelect()
for i in range(len(test_list)):
if test_list[i] in EMDTestsDict.keys():
EMDTestsDict[test_list[i]]()
def UserSelect():
message = "Which EMD tests would you like to run?"
title = "EMD Test Selector"
tests = ["emdtest1",
"emdtest2",
"emdtest3"]
selected_master = multchoicebox(message, title, tests)
return selected_master
if __name__ == '__main__':
main()
You're putting modules into the dict, when you want to put functions in it. What you're doing is the equivalent of saying
import os
os()
Which, of course, makes no sense. If emdtest1, emdtest2, and emdtest3 are .py files with functions in them, you want:
from emdtest1 import function_name
Where function_name is the name of your function.
You need to import the functions rather than the module ... for example , if you have a file called emdtest1 with a defined function emdtest1, you'd use:
from emdtest1 import emdtest1

Categories

Resources