How to import a .hs file in Haskell - haskell

I have made a file called time.hs. It contains a single function that measures the execution time another function.
Is there a way to import the time.hs file into another Haskell script?
I want something like:
module Main where
import C:\Haskell\time.hs
main = do
putStrLn "Starting..."
time $ print answer
putStrLn "Done."
Where time is defined in the 'time.hs' as:
module time where
Import <necessary modules>
time a = do
start <- getCPUTime
v <- a
end <- getCPUTime
let diff = (fromIntegral (end - start)) / (10^12)
printf "Computation time: %0.3f sec\n" (diff :: Double)
return v
I don't know how to import or load a separate .hs file. Do I need to compile the time.hs file into a module before importing?

Time.hs:
module Time where
...
script.hs:
import Time
...
Command line:
ghc --make script.hs

If the module Time.hs is located in the same directory as your "main" module, you can simply type:
import Time
It is possible to use a hierarchical structure, so that you can write import Utils.Time.
As far as I know, the way you want to do it won't work.
For more information on modules, see here Learn You a Haskell, Making Our Own Modules.

Say I have two files in the same directory: ModuleA.hs and ModuleB.hs.
ModuleA.hs:
module ModuleA where
...
ModuleB.hs:
module ModuleB where
import ModuleA
...
I can do this:
ghc -I. --make ModuleB.hs
Note: The module name and the file name must be the same. Otherwise it can't compile. Something like
Could not find module '...'
will occur.

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".

Getting script filepath from an imported python module

Let say I have a file a/b/c.py with following content.
import mymodule
a = mymodule.MyClass()
print(a.scriptpath)
I want a.scriptpath to print a/b/c.py. Essentially, what I am asking: Is there a way for MyClass.__init__ or mymodule.__init__.py to know from which file they are being called?
Why not just instantiate the class with that information:
a = mymodule.MyClass(__file__)

python packaging results in import error

I have a boost python generating a shared object to be used with python in /home/user/service/org/boost_py.so (This folder does not contain a __init__.py)
and /home/user/service is part of sys.path so when I need to use this ,just do
import org.boost_py #works
Now I have added a pure python module in a different directory.
/home/user/service/pure_python/org/
__init__.py
tester.py
__init__.py contains
__import__('pkg_resources').declare_namespace(__name__)
Now when sys.path is
['/home/user/service/','/home/user/service/pure_python']
and I
import org.boost_py #ImportError: No module named 'org.boost_py'
but I can import org.tester. How to import both org.tester and org.boost_py ? (I cannot change the location of either)
update:
Found pth file with following contents in pure_python directory
import sys, types, os;
p = os.path.join(sys._getframe(1).f_locals['sitedir'], *('org',));
ie = os.path.exists(os.path.join(p,'__init__.py'));
m = not ie and sys.modules.setdefault('org', types.ModuleType('org'));
mp = (m or []) and m.__dict__.setdefault('__path__',[]);
(p not in mp) and mp.append(p)
Apparently there is no file or directory boost_py in 'pure_python/org ', this produces the error.
If it exists please edit the question!
Alternatively, the path of the boost could be not in the path browser, then it just wont recognize the file.

Haskell error Not in scope: data constructor

I wrote some simple module in Haskell and then import it in other file. Then I'm trying to use functions with data constructors from my module — there is an error Not in scope: data constructor: <value>. How can I fix it?
Note: when I'm using it in interpreter after importing — all is good without errors.
My module Test.hs:
module Test (test_f) where
data Test_Data = T|U|F deriving (Show, Eq)
test_f x
| x == T = T
| otherwise = F
And my file file.hs:
import Test
some_func = test_f
No error if I'm writing in interpreter:
> :l Test
> test_f T
T
In interpreter I'm trying to execute some_func T, but there is an error. And how can I use class Test_Data in my file to describe annotations?
You aren't exporting it from your module:
module Test (test_f, Test_Data(..)) where
The (..) part says "export all constructors for TestData".
You have an explicit export list in your module Test:
module Test (test_f) where
The export list (test_f) states that you want to export the function test_f and nothing else. In particular, the datatype Test_Data and its constructors are hidden.
To fix this, either remove the export list like this:
module Test where
Now all things will be exported.
Or add the datatype and its constructors to the export list like this:
module Test (test_f, Test_Data(..)) where
The notation Test_Data(..) exports a datatype with all corresponding constructors.

Cabal rebuild on embedded file change

I'm using the file-embed package thusly:
import qualified Data.ByteString as B
import qualified Data.ByteString.Internal as B (w2c)
import qualified Data.FileEmbed as E
initWindow = do
b <- Gtk.builderNew
let glade = map B.w2c $ B.unpack $ $(E.embedFile "window.glade") in
Gtk.builderAddFromString b glade
...
Is it possible to make cabal rebuild this file even when only the glade file changes?
Support for this will be/has been added in GHC 7.4/7.6. The problem is that the compiler doesn't allow TemplateHaskell splices to add file dependencies yet. See this ticket for more information.
When this change lands, you can use the following code to create a new embedFile' function:
import Data.FileEmbed
import Language.Haskell.TH.Syntax
import Language.Haskell.TH.Lib
embedFile' :: FilePath -> Q Exp
embedFile' path = do
qAddDependentFile path
embedFile path
This has to be in a separate module from where you use the TH function.

Resources