SyntaxError: not a chance — What is this error? - python

I tried to execute the following code on a Python IDLE
from __future__ import braces
And I got the following error:
SyntaxError: not a chance
What does the above error mean?

You have found an easter egg in Python. It is a joke.
It means that delimiting blocks by braces instead of indentation will never be implemented.
Normally, imports from the special __future__ module enable features that are backwards-incompatible, such as the print() function, or true division.
So the line from __future__ import braces is taken to mean you want to enable the 'create blocks with braces' feature, and the exception tells you your chances of that ever happening are nil.
You can add that to the long list of in-jokes included in Python, just like import __hello__, import this and import antigravity. The Python developers have a well-developed sense of humour!

The __future__ module is normally used to provide features from future versions of Python.
This is an easter egg that summarizes its developers' feelings on this issue.
There are several more:
import this will display the zen of Python.
import __hello__ will display Hello World....
In Python 2.7 and 3.0, import antigravity will open the browser to a comic!

It means that writing Python code like:
def hello() {
print("Hello");
print("World");
}
instead of
def hello():
print("Hello")
print("World")
will never happen. One is both faster to type and easier to understand. Can you tell which one?
Oh, and someone made this.

Related

Python module importing itself with leading underscore but there is no corresponding .py file

In the PyBluez source code I've noticed a couple things I haven't seen before. This file named widcomm.py starts with the following:
from .btcommon import *
import socket
import struct
import threading
import os
import _widcomm
In the previous directory, there is no _widcomm.py or another widcomm.py. I've read that modules with a leading underscore might be "private" or accelerated, but I can't find anything about a module seemingly importing itself with an underscore.
A few lines under that you get this interesting function:
def dbg (*args):
return
sys.stdout.write (*args)
sys.stdout.write ("\n")
Am I correct in thinking the code under return has no way of ever being executed? As far as I can tell this function serves no purpose.
What exactly is going on here?
According to the setup file of this Python package,
ext_modules.append(Extension('bluetooth._widcomm',
include_dirs=["%s\\Inc" % WC_BASE],
define_macros=[('_BTWLIB', None)],
library_dirs=["%s\\Release" % WC_BASE],
libraries=["WidcommSdklib", "ws2_32", "version", "user32",
"Advapi32", "Winspool", "ole32", "oleaut32"],
sources=["widcomm\\_widcomm.cpp",
"widcomm\\inquirer.cpp",
"widcomm\\rfcommport.cpp",
"widcomm\\rfcommif.cpp",
"widcomm\\l2capconn.cpp",
"widcomm\\l2capif.cpp",
"widcomm\\sdpservice.cpp",
"widcomm\\util.cpp"]))
the _widcomm import refers to an extension module which is built from the _widcomm.cpp and related C++ source files.
Regarding the obscure return statement.
You can push the blame-button on the github you linked and there you'll see following comment for the return:
suppress debugging messages
Below that return there are said debugging-messages printing the arguments to stdout. So the return is there to not execute those messages that where there before the return. Like you guessed and #mkrieger1 commented those statements will never be executed as long the return is in place.

Python 3.5: Importing a specific function from a file with a space in its name

I am trying to import just one function from a .py file which has a space in its title. Due to external constraints, I cannot rename the file.
My first try was:
from File 1 import my_func
But that got a SyntaxError. Following advice on other StackOverflow, I found ways to import all the functions from a module/file:
V1:
exec(open("File 1.py").read())
V2:
globals().update(vars(__import__('File 1')))
However, I would like to only import my_func. I would also prefer to do this without using other modules like importlib. Any help is very much appreciated, I am still learning!
Editing the answer as requsted:
Source: How do you import a file in python with spaces in the name?.
Importing single function from a module with spaces in name without using importlib is simply impossible, since your only weapon here is __import__.
Your only option is to import the whole module and only keep functions you like. But it still imports the whole module.
Important notice
Getting rid of spaces and other non-alphanumeric symbols from module names is strongly recommended.
Example
File 1.py
def foo():
print("Foonction.")
def spam():
print("Get out!")
main.py
globals()["foo"] = getattr(__import__("File 1"),"foo")

python get the script which imported my script

I want to make my own programming language based on python which will provide additional features that python wasn't provide, for example to make multiline anonymous function with custom syntax. I want my programming language is so simple to be used, just import my script, then I read the script file which is imported my script, then process it's code and stop anymore execution of the script which called my script to prevent error on syntax...
Let say there are 2 py file, main.py and MyLanguage.py
The main.py imported MyLanguage.py
Then how to get the main.py file from MyLanguage.py if main.py can be another name(Dynamic Name)?
Additional information:
I using python 3.4.4 on Windows 7
Like Colonder, I believe the project you have in mind is far more difficult than you imagine.
But, to get you started, here is how to get the main.py file from inside MyLanguage.py. If your importing module looks like this
# main.py
import MyLanguage
if __name__ == "__main__":
print("Hello world from main.py")
and the module it is importing looks like this, in Python 3:
#MyLanguage.py
import inspect
def caller_discoverer():
print('Importing file is', inspect.stack()[-1].filename)
caller_discoverer()
or (edit) like this, in Python 2:
#MyLanguage.py
import inspect
def caller_discoverer():
print 'Importing file is', inspect.stack()[-1][1]
caller_discoverer()
then the output you will get when you run main.py is
Importing file is E:/..blahblahblah../StackOverflow-3.6/48034902/main.py
Hello world from main.py
I believe this answers the question you asked, though I don't think it goes very far towards achieving what you want. The reason for my scepticism is simple: the import statement expects a file containing valid Python, and if you want to import a file with your own non-Python syntax, then you are going to have to do some very clever stuff with import hooks. Without that, your program will simply fail at the import statement with a syntax error.
Best of luck.

"Unused wild import": Why?

Whenever I import from another module using an asterisk (from <anymodule> import *) I am fined with an "Unused wild import"-warning. It appears as if this is not the right way to do the import, but why does that syntax exist if we shouldn't be using it?
That message just tells you that you are importing features from a module that you don't need, which means you should probably import just what you need. You shuld simply use from foobar import x, y where x and y are the elements you actually need.
The syntax from foobar import * is more useful in the command-line interpreter when you don't want to think or type many more characters for little benefit. But in a real project, you should not use that syntax since if you use it, it will not be clear which feature from the module you are going to use.

Writing Python 2.7 code that is as close to Python 3.x syntax as possible

Since Django doesn't yet support Python 3.x, I'm using Python 2.7. However, I'd like to go ahead and start familiarizing myself with the new Python 3.x syntax as much as possible. Which leads me to the question:
What is the best way to write Python 2.7 code that will be as compatible as possible with Python 3.x?
I know that running python -3 will
Warn about Python 3.x incompatibilities that 2to3 cannot trivially fix.
However, I'm interested in getting used to Python 3.x syntax while still using Python 2.7.
For instance, it seems that I should be using the following imports to my code:
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
The above four __future__ import statements are required as of Python 3.0, but not required in 2.7 as described in Python 2.7.3's documentation 27.11. Future Statement Definitions
What else?
Many modules these days get rewritten in a way that allows execution on both Python 2 and Python 3. This turns out to be not very hard at all, and in the future it will be very easy to just drop Python 2 support.
Take a look at the six module that helps with this task, encapsulating many of the differences in a convenient way:
Six provides simple utilities for
wrapping over differences between
Python 2 and Python 3.
Its website (and of course, code) lists a lot of ways to make this possible.
Put the following code into a py3k.py module and import it like this:
from py3k import *. You need to put it in every file though, but you can even leave it there if nobody uses Python 2.x anymore or you could just search & replace the import line with whitespace and then remove the file.
try:
from future_builtins import *
except ImportError:
pass
try:
input = raw_input
range = xrange
except NameError:
pass
And this is how my template file looks:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
from __future__ import division, absolute_import, \
print_function, unicode_literals
from utils.py3k import * # #UnusedWildImport
#
You also need to use the new exception syntaxes, ie no more
try:
raise Exception, "Message"
except Exception, e:
pass
instead you should do:
try:
raise Exception("Message")
except Exception as e:
pass
Also make sure you prefix all your binary strings with a b, ie:
b'This is a binary string'
For a more complete cover of this topic, see http://python3porting.com/noconv.html
Many Python IDE's can be of big help here.
PyCharm, for example, can be configured to check for compatibility with any range of versions,
and report issues at any level of severity:
try:
input = raw_input
range = xrange
except NameError:
pass
Are two ones that spring to mind...
I propose you to give a try for future library. From their site:
python-future is the missing compatibility layer between Python 2 and Python 3. It allows you to use a single, clean Python 3.x-compatible codebase to support both Python 2 and Python 3 with minimal overhead.
It provides future and past packages with backports and forward ports of features from Python 3 and 2. It also comes with futurize and pasteurize, customized 2to3-based scripts that helps you to convert either Py2 or Py3 code easily to support both Python 2 and 3 in a single clean Py3-style codebase, module by module.
Notable projects that use python-future for Python 2/3 compatibility are Mezzanine and ObsPy.
Avoing range() and zip(), using xrange() and itertools.izip() instead.

Categories

Resources