0

I have written a simple function that allows me to parse a string with a variable type (following the method described in this SO question Lexical cast from string to type). I have a module called ascii_tools that contains the following function:

def get_builtin(name):
    return getattr(__builtins__, name)

So, this works as follows.

get_builtin(desired_type)(some_input_string)

This parses my string for desired_type='float' or 'int', saving me some hard-coding for some applications requiring string parsing.

When I define the get_builtin function directly into a python interpreter, this function behaves properly. However, when I try to call this function via ascii_tools.get_builtin('float'), I get the following error:

AttributeError: 'dict' object has no attribute 'float'

Same error occurs for 'int' input. This seemed strange, since the method works just fine when defined in the global namespace of the interpreter. So I checked the output of pdb, which is:

NameError: name 'ascii_tools' is not defined

This must have something to do with the namespace of builtins. Maybe calls to builtins somehow check the namespace of the module the call is nested in, and this is causing the problem?

Community
  • 1
  • 1
aph
  • 1,765
  • 2
  • 19
  • 34
  • The `NameError` is unrelated. – Martijn Pieters Jan 27 '15 at 15:30
  • Thanks for pointing me to the relevant post, @MartijnPieters , although for some reason "import builtins" does not work for me "ImportError: No module named builtins" – aph Jan 27 '15 at 15:36
  • 1
    On Python 3 the module has been renamed to [`builtins`](https://docs.python.org/3/library/builtins.html) (no underscores). The Python 2 version of the documentation should have included a banner at the top informing you of the name change but I see that that is missing; I'll file a Python documentation bug report. – Martijn Pieters Jan 27 '15 at 15:40
  • Ok, but given that I am running on python 2.7.x, how can I import the builtins module so that I can solve my problem? Without being able to do that, I cannot implement your solution. – aph Jan 27 '15 at 15:43
  • 1
    Sorry, got my posts mixed up. In Python 2 it is called [`__builtin__`](https://docs.python.org/2/library/__builtin__.html). – Martijn Pieters Jan 27 '15 at 15:46
  • Thanks for sticking with me, @MartijnPieters , problem solved. – aph Jan 27 '15 at 15:55
  • Any chance you can point me to how I can call the builtins module so that my call will be both python 2 and 3 compatible? Maybe with a __future__ call somehow? – aph Jan 27 '15 at 15:56
  • 1
    Use exception handling; `try: import __builtin__ as builtins`, `except ImportError: import builtins`. – Martijn Pieters Jan 27 '15 at 15:57
  • Durr, that should have been obvious. Thanks again for all the help! – aph Jan 27 '15 at 16:00

0 Answers0