Get built-in function from the function name - python

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'

Related

Python full module path of a function

Is it possible to obtain a string containing the whole namespace from which a function was imported?
I would like some code like the following:
import math
import numpy
whole1 = get_whole_namespace(math.sin)
whole2 = get_whole_namespace(numpy.sin)
The resulting whole1 should be the string "math.sin", and the resulting whole2 should be the string "numpy.sin". Is there any standard library (or third party) functionality equivalent to the get_whole_namespace function in my example?
I originally thought that my desired result should be available in some dunder method or attribute. But the __name__ attribute of both math.sin and numpy.sin is the string "sin".
The math.sin function also has a __qualname__ attribute (which is the string "sin"), and a __module__ attribute (which is the string "math").
The numpy.sin function does not have either __qualname__ or __math__ attributes.
I am using Python 3.10.6 and NumPy 1.23.4.

Dynamically acessing a built-in type object by name

In Python, it is possible to dynamically access a class object by name with getattr:
getattr(module, "<class_name>")
How can I do that for built-in type objects (int, str, list, etc.)?
I would like to use the same trick, but I don't know in which module built-in types are defined.
Finally I have found what I was looking for by myself:
import builtins
getattr(builtins, "<type_name>")
Note. — Do not use the __builtins__ module as it is an implementation detail (see https://docs.python.org/3/library/builtins.html) of the CPython interpreter.

How to check the type of an object against the type "function"

I am wiriting a script in which I would like to verify if a given argumente to a function is itself a function. I have checked in the IDLE the type() of that argument.
Let us assume that the argumente is called a and that I know that a is a function.
When I type type(a) in the Shell, this gets printed:
<class 'function'>
But if I try to type this:
type(add) == function
It gives me a NameError: name 'function' is not defined
(That was not my only attempt, but if I put them all here this will get too long)
I think I understand that part, because I think function is not a keyword like int or float, which lets me do conditionals like type(3) == int
But, knowing this, how can I check if something is from a given built-in type, if that type does not have a specific keyword (or maybe, those keywords are not that well-known)
Thanks in advance.
You can use the isinstance built-in to check if the type of a variable conforms to a type of a function. Unfortunately, as there is no short hand to create a function type just like int you can import types and check with types.FunctionType
>>> import types
>>> isinstance(add, types.FunctionType)
True
you can also import isfunction from inspect to perform the same check
import inspect
inspect.isfunction(add)
from inspect import isfunction
isfunction(a)

Inconsistency in python help('string') versus help(list)?

When I type help('string') in the python interpreter I get information about the string class. There,upper() is indicated as a function. Yet I can only call it as a method like "hi".upper() instead of upper("hi").
So one could assume that any method will be indicated as a function in the docstrings of the built in modules. Yet when I do help('list') , methods of the list class are indicated as methods in the docstrings!!
Why is this so? Only because the person who wrote the doctrings was inconsistent or that different people wrote it? Or do these methods(the ones called 'functions' versus the ones called 'methods' in the docstrings) actually have different properties?
When you searched for help('string'), you were looking for the docstrings of the string module. If you do help(str) or help('str') you'll get the docstrings of the str type, and here upper appears as a method!
As you can see here, the function upper from the string module is actually a function and not a method:
>>> upper('hi')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'upper' is not defined
>>> 'hi'.upper() # method from the str type
'HI'
>>> from string import upper
>>> upper('hi') # function from the string module
'HI'
You mean to do help('str'), not help('string'). str is a type, string is a module providing functions for working with strings.
You are creating an instance of that object and then calling help on that instance.
So these all work:
help(1)
help({})
help([])
help('')
help(dir)
help(help)
Help grabs the docstring for that instance, and gives it back to you.
When you create your own objects, you can put in useful docstrings or whatever you want.
There's nothing wrong with what you see.
>>> help('string')
Will show you the string module documentation. And it looks like there's an upper function inside:
>>> import string
>>> string.upper('hello')
'hello'
I'd say that this upper is the same that is called if you do:
>>> 'hello'.upper()
But I'm not sure.
Notice that a string '' is a str type not a string type. This means that you're probably looking for:
>>> help('str')
And here you'll see too the str.upper method.
This is because 'string' is a string. So is 'list'
To get a similar result for lists, try help([])

how to isinstance(x, module)?

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__)

Categories

Resources