I need to test if a variable is a module or not. How to do this in the cleanest way?
I need this for initializing some dispatcher function and I want that the function can accept either dict or module as an argument.
>>> import os, types
>>> isinstance(os, types.ModuleType)
True
(It also works for your own Python modules, as well as built-in ones like os.)
I like to use this so you don't have to import the types module:
isinstance(amodule, __builtins__.__class__)
Related
Say you only wanted to call a regular expression a single time in you code. As far as I am aware, this means that you then need to do import re somewhere before your call of a function from re. Is it possible to combine this with the function call, in-line?
I thought maybe something like this would work
print(import re; re.search(r'<regex>', <string>).group())
but it just threw an error saying invalid syntax at the point of the import. This leads me to believe that the only way to do this is
import re
print(re.search(r'<regex>'), <string>).group())
Answering the question:
Can You Perform an Inline Import in Python?
You can use the built-in importlib module:
print(importlib.import_module('re').search("h", "hello").group())
Output:
'h'
Of course, it would require you to import the importlib module first:
import importlib
print(importlib.import_module('re').search("h", "hello").group())
From the documentation:
The import_module() function acts as a simplifying wrapper around importlib.__import__(). This means all semantics of the function are derived from importlib.__import__(). The most important difference between these two functions is that import_module() returns the specified package or module (e.g. pkg.mod), while __import__() returns the top-level package or module (e.g. pkg).
Like we have python modules in the standard library from which we can import methods and use them, is there also a module where all the built-in functions are defined?
If yes, how can I view that module?
The builtins (Python 3) or __builtin__ (Python 2) module provides access to them.
This is even useful sometimes if you rebind the name of a builtin, eg list = [1, 2, 3]. You generally shouldn't do that, but if you do you can still access the builtin list constructor as builtins.list.
On python3, import builtins or import __builtin__ for older versions
You can check any modules content with the dir function
In Python, when we import something:
import Module
when we later want to use functions created in the module we have to say
Module.foo()
Is there any way to "attach" the module so that if I simply call
foo()
It knows that I mean to use the foo defined in Module, as long as the name does not conflict with any name in the current file?
from Module import *
This imports all symbols in Module unless overriden by __all__.
You can also explicitly import (which is better) only the symbols you actually need.
from Module import foo
It's typically preferred to use the later. Even better is to use the module as namespacing. There's nothing wrong with Module.foo() vs. foo(). Once your program gets fairly large, this will help you quite a bit with refactoring.
You can just do from module import foo, and then refer to foo() directly.
I am not really a programmer but a computational statistician, so I may understand complex algorithms but not simple programming constructs.
My original problem is to check within a function if a module function is callable. I looked around and decided to go for a try (call function) - except (import module) to make it simple. I'd love to search sys.mod for this but I am running in some identifiability problems.
My current problem is that there are many ways of importing a function from a module: import module will define the function as module.function but from module import function will define it as function. Not to mention from module import function as myfunction. Therefore the same function can be called in several different ways.
My question is: is there a unique "signature" for a function that can be traced if the module is loaded? It would be fantastic to have the actual call alias to it.
ps besides: mod is mathematical function and sys.mod returns a list of loaded modules, but python (2.7) does not complain when you shadow the built-in mod function by doing the following, from sys import mod. I find this a bit awkward - is there any way to avoid this sort of shadowing programatically?
My original problem is to check within a function if a module function is callable.
By definition, all functions are callable. This will test if an object is callable: http://docs.python.org/library/functions.html#callable
Therefore the same function can be called in several different ways.
Yes, but it will be the same object. You can just use f is g to test if f and g are the same object.
Update: Why would you need to use a unique ID? Seriously, don't do this. You have is for identity tests, and the __hash__ method to define the hash function applicable.
It would be fantastic to have the actual call alias to it.
Not sure at all what you mean, but I think you just want it to always be one object. Which it is already.
mod is mathematical function and sys.mod returns a list of loaded modules, but python (2.7) does not complain to from sys import mod. I find this a bit awkward?
Then don't do that. You know about the import ... as syntax. Also mod is not by default in the global namespace (the operator % is for that).
Finally, python does complain about your import line:
>>> from sys import mod
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name mod
(Thanks to kindall for pointing this out).
Assume I have a module with the following:
def foo(): pass
bar = foo
You can easily see that they're the same functions by using is or id():
>>> import demo
>>> from demo import *
>>> demo.foo is foo
True
>>> id(demo.foo) == id(foo)
True
>>> demo.bar is foo
True
They all refer to the same code object, it's just stored under different names in the scope dictionary.
# define modulus f
def mod(a,b):
return b % a
print mod(5,2)
alias:
modulus=mod
print modulus(5,2)
this is pretty pythonic construct, and it is pretty intuitive for mathematicians
different ways of import serve to help you place a function into different "name space" for later use in your program, sometimes you wish to use a function a lot so you choose variant that is shorter to write.
you can also do something like:
myat=math.atanh
to make alias in another "name space"
and use it as:
myat(x)
as it would use math.atanh(x) - becomes shorter to write
Typical programmers approach would be define all you want to use and then use it. What you are trying in my belief is to do it "lazy" => import module when you need a function. That is why you wish to know if function is "callable".
Python is not functional programming language (e.g. like haskel) so that you can load or refer "on demand".
hope this helps.
How can I get the int(), float(), dict(), etc. callables from their names? For example, I'm trying to save Python values to xml and storing the variable type as a string. Is there a way to get the callable from the string when converting from string back to the Python type?
Normally I would do something like getattr(myobj, 'str'), but there is no module to use as the first argument for these built-in conversion functions. I've also tried getattr(object, 'str'), but this doesn't work either since these functions are not part of the base 'object' type, merely globals to the language.
Normally I would do something like getattr(myobj, 'str'), but there is no module to use as the first argument for these built-in conversion functions.
Wrong, there is:
import __builtin__
my_str = getattr(__builtin__, "str")
(In Python 3.x: import builtins)
You don't need to import anything
vars(__builtins__)['dict']
vars(__builtins__)['float']
vars(__builtins__)['int']
etc.
One quick way is to invoke it from the __builtin__ module. For example
>>> import __builtin__
>>> __builtin__.__dict__['str'](10)
'10'