This question already has answers here:
Finding the source code for built-in Python functions?
(8 answers)
Closed 6 years ago.
I am searching through method/class declarations in Pycharm and I made it down to __builtin__.py, but there does not appear to be any code written in this module.
Here is the snippet that I came across:
def hasattr(p_object, name): # real signature unknown; restored from __doc__
"""
hasattr(object, name) -> bool
Return whether the object has an attribute with the given name.
(This is done by calling getattr(object, name) and catching exceptions.)
"""
return False
Where is the code that is actually executed when I call hasattr()? Is the line # real signature unknown; restored from __doc__ a clue as to why there is no code here?
I am not interested in changing anything. I am simply surprised that there is no code written here.
They are built in functions.
It means that they are a direct calls to methods embedded in python binaries. Simply, the python code for them doesn't exist.
Related
This question already has an answer here:
What is the type hint for a (any) python module?
(1 answer)
Closed 2 years ago.
I'm building an API to allow for plugins in an application I'm working on. I'm using importlib.import_module to import the plugins. Clearly I have no idea what modules are going to be imported ahead of time. Is there a way to identify the return type as a generic module on the method I'm using to do the imports?
def import_plugin(plugin_name: str) -> <Some generic module type>:
# conditional tests here...
return importlib.import_module("plugins.{}".format(plugin_name))
The type of a module is given by types.ModuleType in the types module.
import types
type(types) is types.ModuleType
# => True
Python uses duck typing, so I recommend assuming it is a module, and if it is not let the user handle it. If you really want to get the type, use types.ModuleType as khelwood said.
This question already has an answer here:
What is the type hint for a (any) python module?
(1 answer)
Closed 2 years ago.
I have a function that takes in a package and returns a list of classes in it (as well as subpackages) that inherits from foo.
def list_foo_classes_from_package(package) -> List[foo]:
...
code to find attribute that is issubclass(attribute, foo)
...
return list_of_foo_classes
import boo
class_list = list_classes(boo)
I want to type hint the input package. however module is not a keyword. The closest thing I found was types.ModuleType, i.e.
def list_classes_from_package(self, package: types.ModuleType) -> List[foo]:
However I get a warning:
expected type ModuleType, got "__init__.py" instead
How do I type hint package as parameter to a function?
Turned out types.ModuleType was correct. It was an issue with Pycharm (thanks #user2357112 supports Monica). When searching for "Pycharm module type hint" on google led me to this answer.
This question already has answers here:
How do I type hint a method with the type of the enclosing class?
(7 answers)
Closed 3 years ago.
I'm currently working on creating a python linear algebra module for fun and for practice with the language. I recently tried to add type annotations to the module, as such:
class Vector:
# Various irrelevant implementation details
def __add__(self, other: Vector) -> Vector:
# More implementation details....
However, when I try to import this, it spits out a NameError: Name 'Vector' is not defined. I acknowledge that this question has already been answered, in a form, here, but it doesn't seem to wholly provide an answer for my situation.
What I'd like to know:
I've defined the class literally in this file. Why does it say the name isn't defined?
How do I define Vector in such a way that it can be used for annotations (as a type)?
You have a forward declaration; functions (to be bound as methods) are created before the class is, so the name Vector doesn't yet exist. Only when all of the class body has been executed, can Python create the class object and bind the name Vector to it.
Simply use a string with the name instead:
class Vector:
# Various irrelevant implementation details
def __add__(self, other: 'Vector') -> 'Vector':
# More implementation details....
This doesn't affect how your IDE sees the declaration; strings are looked up once the whole module is loaded, and are resolved as a valid Python expression in the current context. Since the class Vector exists once the whole module is loaded, the string 'Vector' can properly be converted to the class object.
Also see the specification on forward references:
When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.
[...]
The string literal should contain a valid Python expression [...] and it should evaluate without errors once the module has been fully loaded.
As of Python 3.7 you can make all annotations in a given module behave like forward annotations (without enclosing them in a string literal), by adding the from __future__ import annotations directive at the top of the module. It was originally planned for this to be the default in Python 3.10 and up, but this decision has now been deferred indefinitely. See PEP 563 -- Postponed Evaluation of Annotations for details. Note that outside of annotations you may still need to use forward reference syntax (string literals), e.g. in a type alias (which is a regular variable assignment as far as Python is concerned).
If you are using Python 3.7 and above. Take a look at Postponed evaluation of annotations
Since Python 3.7, it will be allowed, just add:
from __future__ import annotations
And also note that
It will become the default in Python 3.10.
This question already has answers here:
How to restore a builtin that I overwrote by accident?
(3 answers)
Closed 9 years ago.
I was asked to add some feature to the code originally written by other guys.
There is a python code defines a function which overwrites the build in open function
def open(xxx):
...
I would like to access original open function in the same python file.
The best way is to change the name of self defined open. But I prefer not to change it since it is a hug system which may have many other files access to this method.
So, is there a way to access the build in open even if it has been overwritten?
Python 2:
>>> import __builtin__
>>> __builtin__.open
<built-in function open>
Python 3:
>>> import builtins
>>> builtins.open
<built-in function open>
Don't use __builtins__ :
From the docs:
CPython implementation detail: Users should not touch __builtins__; it
is strictly an implementation detail. Users wanting to override values
in the builtins namespace should import the __builtin__ (no āsā)
module and modify its attributes appropriately.
>>> __builtins__.open
<built-in function open>
Works the same in Python2 and Python3
A more general way to access an overwritten version of a function is this:
oldVersionOfOpen = open
def open(...):
oldVersionOfOpen(...)
In fact, functions are only variables with a value (which is a callable), so you also can assign them to other variables to store them.
You could even do it like this:
def newOpen(...):
pass # do whatever you'd like to, even using originalOpen()
originalOpen, open = open, newOpen # switch
This question already has answers here:
How can I get the source code of a Python function?
(13 answers)
Closed 8 years ago.
Is there a way to view the source code of a function, class, or module from the python interpreter? (in addition to using help to view the docs and dir to view the attributes/methods)
If you plan to use python interactively it is hard to beat ipython. To print the source of any known function you can then use %psource.
In [1]: import ctypes
In [2]: %psource ctypes.c_bool
class c_bool(_SimpleCData):
_type_ = "?"
The output is even colorized. You can also directly invoke your $EDITOR on the defining source file with %edit.
In [3]: %edit ctypes.c_bool
>>> import inspect
>>> print(''.join(inspect.getsourcelines(inspect.getsourcelines)[0]))
def getsourcelines(object):
"""Return a list of source lines and starting line number for an object.
The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a list of the lines
corresponding to the object and the line number indicates where in the
original source file the first line of code was found. An IOError is
raised if the source code cannot be retrieved."""
lines, lnum = findsource(object)
if ismodule(object): return lines, 0
else: return getblock(lines[lnum:]), lnum + 1