Is there any way you can import local procs from other files in the same directory? - nim-lang

If you have 2 Python files in the same directory, you can do the following:
something.py
def returnSomething():
return True
index.py
from something import returnSomething
test=returnSomething()
Can something similar be done in Nim by calling their procs?

Yes, you can, you just need to export the proc by adding * (the export marker) after the name of it - https://nim-lang.org/docs/manual.html#procedures-export-marker :)
# something.nim
proc returnSomething*(): bool =
result = true
# index.nim
import something
test = returnSomething()
You can also replace import something with from something import returnSomething, but it's a personal preference.
I think it might be good for you to read https://narimiran.github.io/nim-basics/ which covers most of Nim basics :)

Related

Importing a daily changing variable name in python [duplicate]

I'm writing a Python application that takes a command as an argument, for example:
$ python myapp.py command1
I want the application to be extensible, that is, to be able to add new modules that implement new commands without having to change the main application source. The tree looks something like:
myapp/
__init__.py
commands/
__init__.py
command1.py
command2.py
foo.py
bar.py
So I want the application to find the available command modules at runtime and execute the appropriate one.
Python defines an __import__() function, which takes a string for a module name:
__import__(name, globals=None, locals=None, fromlist=(), level=0)
The function imports the module name, potentially using the given globals and locals to determine how to interpret the name in a package context. The fromlist gives the names of objects or submodules that should be imported from the module given by name.
Source: https://docs.python.org/3/library/functions.html#__import__
So currently I have something like:
command = sys.argv[1]
try:
command_module = __import__("myapp.commands.%s" % command, fromlist=["myapp.commands"])
except ImportError:
# Display error message
command_module.run()
This works just fine, I'm just wondering if there is possibly a more idiomatic way to accomplish what we are doing with this code.
Note that I specifically don't want to get in to using eggs or extension points. This is not an open-source project and I don't expect there to be "plugins". The point is to simplify the main application code and remove the need to modify it each time a new command module is added.
See also: How do I import a module given the full path?
With Python older than 2.7/3.1, that's pretty much how you do it.
For newer versions, see importlib.import_module for Python 2 and Python 3.
Or using __import__ you can import a list of modules by doing this:
>>> moduleNames = ['sys', 'os', 're', 'unittest']
>>> moduleNames
['sys', 'os', 're', 'unittest']
>>> modules = map(__import__, moduleNames)
Ripped straight from Dive Into Python.
The recommended way for Python 2.7 and 3.1 and later is to use importlib module:
importlib.import_module(name, package=None)
Import a module. The name argument specifies what module to import in absolute or relative terms (e.g. either pkg.mod or ..mod). If the name is specified in relative terms, then the package argument must be set to the name of the package which is to act as the anchor for resolving the package name (e.g. import_module('..mod', 'pkg.subpkg') will import pkg.mod).
e.g.
my_module = importlib.import_module('os.path')
Note: imp is deprecated since Python 3.4 in favor of importlib
As mentioned the imp module provides you loading functions:
imp.load_source(name, path)
imp.load_compiled(name, path)
I've used these before to perform something similar.
In my case I defined a specific class with defined methods that were required.
Once I loaded the module I would check if the class was in the module, and then create an instance of that class, something like this:
import imp
import os
def load_from_file(filepath):
class_inst = None
expected_class = 'MyClass'
mod_name,file_ext = os.path.splitext(os.path.split(filepath)[-1])
if file_ext.lower() == '.py':
py_mod = imp.load_source(mod_name, filepath)
elif file_ext.lower() == '.pyc':
py_mod = imp.load_compiled(mod_name, filepath)
if hasattr(py_mod, expected_class):
class_inst = getattr(py_mod, expected_class)()
return class_inst
Using importlib
Importing a source file
Here is a slightly adapted example from the documentation:
import sys
import importlib.util
file_path = 'pluginX.py'
module_name = 'pluginX'
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
# Verify contents of the module:
print(dir(module))
From here, module will be a module object representing the pluginX module (the same thing that would be assigned to pluginX by doing import pluginX). Thus, to call e.g. a hello function (with no parameters) defined in pluginX, use module.hello().
To get the effect "importing" functionality from the module instead, store it in the in-memory cache of loaded modules, and then do the corresponding from import:
sys.modules[module_name] = module
from pluginX import hello
hello()
Importing a package
To import a package instead, calling import_module is sufficient. Suppose there is a package folder pluginX in the current working directory; then just do
import importlib
pkg = importlib.import_module('pluginX')
# check if it's all there..
print(dir(pkg))
Use the imp module, or the more direct __import__() function.
You can use exec:
exec("import myapp.commands.%s" % command)
If you want it in your locals:
>>> mod = 'sys'
>>> locals()['my_module'] = __import__(mod)
>>> my_module.version
'2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]'
same would work with globals()
Similar as #monkut 's solution but reusable and error tolerant described here http://stamat.wordpress.com/dynamic-module-import-in-python/:
import os
import imp
def importFromURI(uri, absl):
mod = None
if not absl:
uri = os.path.normpath(os.path.join(os.path.dirname(__file__), uri))
path, fname = os.path.split(uri)
mname, ext = os.path.splitext(fname)
if os.path.exists(os.path.join(path,mname)+'.pyc'):
try:
return imp.load_compiled(mname, uri)
except:
pass
if os.path.exists(os.path.join(path,mname)+'.py'):
try:
return imp.load_source(mname, uri)
except:
pass
return mod
The below piece worked for me:
>>>import imp;
>>>fp, pathname, description = imp.find_module("/home/test_module");
>>>test_module = imp.load_module("test_module", fp, pathname, description);
>>>print test_module.print_hello();
if you want to import in shell-script:
python -c '<above entire code in one line>'
The following worked for me:
import sys, glob
sys.path.append('/home/marc/python/importtest/modus')
fl = glob.glob('modus/*.py')
modulist = []
adapters=[]
for i in range(len(fl)):
fl[i] = fl[i].split('/')[1]
fl[i] = fl[i][0:(len(fl[i])-3)]
modulist.append(getattr(__import__(fl[i]),fl[i]))
adapters.append(modulist[i]())
It loads modules from the folder 'modus'. The modules have a single class with the same name as the module name. E.g. the file modus/modu1.py contains:
class modu1():
def __init__(self):
self.x=1
print self.x
The result is a list of dynamically loaded classes "adapters".

I need help creating a directory that gives me the exact date like example /2019/09/03/?

Code looks something like this, Please let me know on changes :
import os
import datetime
path = "/home/xxx/"
current_time = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
command = "mkdir {0}".format(current_time)
os.chdir(path)
os.system(command)
If I understand correctly, this question is for nested directory e.g. 2019/09/03:
import os
import datetime
path = "<define_path>"
current_time = datetime.datetime.now().strftime('%Y/%m/%d/%H/%M/%S')
os.chdir(path)
os.makedirs(current_time)

'spaceship' class is not defined (even though I've imported it?)

I run the main module, which should work correctly. But an error gets returned. 'spaceship' is not defined when I define 's=spaceship(parameters)' why is this I don't get it. I'm using zelle graphics for python. thank you
Functions from main module:
spaceshipGame file
from graphics import *
from spaceshipClass import *
def main():
window=createGraphicsWindow()
runGame(window)
def createGraphicsWindow():
win=GraphWin("Spaceship game",800,800)
return win
def createSpaceship(window,p1,p2,p3,speed,colour):
s=spaceship(window,p1,p2,p3,speed,colour)
return s
def runGame(window):
player=createSpaceship(window,Point(500,500),Point(500,470),Point(520,485),0.5,"red")
player.draw(window)
main()
spaceshipClass file
from spaceshipGame import *
from graphics import *
class spaceship:
def __init__(self,window,p1,p2,p3,speed,colour):
self.p1=p1
self.p2=p2
self.p3=p3
self.speed=speed
self.colour=colour
self.window=window
Never mind, I see the problem. Consult this example for more information:
Simple cross import in python
But the problem is the way you are cross importing, so delete from spaceshipGame import * from spaceshipClass or vise-versa (i.e. delete from spaceshipClass import * from spaceshipGame). You can import individually if you need to like in the example I provided.
There are also many other ways around it if you read the example. One of the easiest would be just merging them in the same file if they need to share a lot of methods.

Creating file path with config file, string.format() and pathlib Path

This seems trivial, but I'm having trouble creating a path using pathlib's Path().
First, I gather user input for the location they want their output directory via a config file.
Then I create an instance variable with the file paths:
import time
from pathlib import Path
class MyStuff():
def __init__(self,
output_file):
self.output_file = output_file
## Setup logging ###
today = time.strftime("%Y%m%d")
now = time.strftime("%Y%d%m_%H:%M:%S")
today_file = "{}_ShortStack.log".format(today)
And next I'm trying to create the log file with today's date. I've tried the following:
log_file = Path("{}{}".format(self.log_path, today_file))
log_file = Path(self.log_path / today_file)
log_file = Path(self.log_path.joinpath(Path(today_file)))
If someone enters:
output_dir =./
on their config file, pathlib keeps putting quotes around it no matter what I try, as shown below:
"./"20181221_ShortStack.log
I've also tried doing this first, to see if it helped. It did not.
self.output_file = Path(output_file)
This should work:
log_file = Path(self.log_path) / today_file
You want the first object to be of type Path, rest can be strings as pathlib takes care of it.
All you need here is os.path.join:
log_file = os.path.join(self.log_path, today_file)
welp. After much fussing around, this did the trick:
log_file = Path(Path(self.log_path) / Path(today_file))

Call a function dynamically from a variable - Python

Ok so I have two files, filename1.py and filename2.py and they both have a function with same name funB. The third file process.py has function that calls function from either files. I seem to be struggling in calling the correct function.
In process.py:
from directoryA.filename1 import funB
from directoryA.filename2 import funB
def funA:
#do stuff to determine which filename and save it in variable named 'd'
d = 'filename2'
# here i want to call funB with *args based on what 'd' is
So i have tried eval() like so:
call_right_funB = eval(d.funB(*args))
but it seems not to work.
Any help is appreciated.
The problem is, you can't use eval() with a combination of a string and a method like that. What you have written is:
call_right_funB = eval('filename'.funB(*args))
What you can do is:
call_right_funB = eval(d + '.funB(*args)')
But this is not very pythonic approach.
I would recommend creating a dictionary switch. Even though you have to import entire module:
import directoryA.filename1
import directoryA.filename2
dic_switch = {1: directoryA.filename1, 2: directoryA.filename2}
switch_variable = 1
call_right_funB = dic_switch[switch_variable].funB(*args)
Hope it helps.

Resources